Replace db_cache_with_key with a parameter on cache_with_key.

(imported from commit f2c600292888ba384ee4acc97c94f1d6f8bc9657)
This commit is contained in:
Tim Abbott 2013-03-13 13:36:58 -04:00
parent 719e24a25b
commit 1580386946
2 changed files with 10 additions and 33 deletions

View File

@ -16,7 +16,7 @@ from zephyr.lib.avatar import gravatar_hash
from zephyr.lib.bugdown import codehilite, fenced_code
from zephyr.lib.bugdown.fenced_code import FENCE_RE
from zephyr.lib.timeout import timeout
from zephyr.lib.cache import db_cache_with_key
from zephyr.lib.cache import cache_with_key
def walk_tree(root, processor, stop_after_first=False):
results = []
@ -94,7 +94,7 @@ class InlineImagePreviewProcessor(markdown.treeprocessors.Treeprocessor):
return root
@db_cache_with_key(lambda tweet_id: tweet_id)
@cache_with_key(lambda tweet_id: tweet_id, cache_name="database")
def fetch_tweet_data(tweet_id):
if settings.TEST_SUITE:
import testing_mocks

View File

@ -3,7 +3,7 @@ from functools import wraps
from django.core.cache import cache as djcache
from django.core.cache import get_cache
def cache_with_key(keyfunc):
def cache_with_key(keyfunc, cache_name=None):
"""Decorator which applies Django caching to a function.
Decorator argument is a function which computes a cache key
@ -14,8 +14,13 @@ def cache_with_key(keyfunc):
def decorator(func):
@wraps(func)
def func_with_caching(*args, **kwargs):
if cache_name is None:
cache_backend = djcache
else:
cache_backend = get_cache(cache_name)
key = keyfunc(*args, **kwargs)
val = djcache.get(key)
val = cache_backend.get(key)
# Values are singleton tuples so that we can distinguish
# a result of None from a missing key.
@ -23,7 +28,7 @@ def cache_with_key(keyfunc):
return val[0]
val = func(*args, **kwargs)
djcache.set(key, (val,))
cache_backend.set(key, (val,))
return val
return func_with_caching
@ -45,31 +50,3 @@ def cache(func):
return key.replace('-','--').replace(' ','-s')
return cache_with_key(keyfunc)(func)
def db_cache_with_key(keyfunc):
"""Decorator which applies Django caching to a function.
Decorator argument is a function which computes a cache key
from the original function's arguments. You are responsible
for avoiding collisions with other uses of this decorator or
other uses of caching."""
def decorator(func):
@wraps(func)
def func_with_caching(*args, **kwargs):
key = keyfunc(*args, **kwargs)
database_cache = get_cache("database")
val = database_cache.get(key)
# Values are singleton tuples so that we can distinguish
# a result of None from a missing key.
if val is not None:
return val[0]
val = func(*args, **kwargs)
database_cache.set(key, (val,))
return val
return func_with_caching
return decorator