diff --git a/zephyr/lib/bugdown/__init__.py b/zephyr/lib/bugdown/__init__.py index ccad1755da..4d6e6ebecb 100644 --- a/zephyr/lib/bugdown/__init__.py +++ b/zephyr/lib/bugdown/__init__.py @@ -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 diff --git a/zephyr/lib/cache.py b/zephyr/lib/cache.py index 17a6252a24..fb5f5560ed 100644 --- a/zephyr/lib/cache.py +++ b/zephyr/lib/cache.py @@ -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