Skip to content

Instantly share code, notes, and snippets.

Created December 11, 2011 07:40
Show Gist options
  • Save anonymous/1459147 to your computer and use it in GitHub Desktop.
Save anonymous/1459147 to your computer and use it in GitHub Desktop.
Cache method results using Django cache framework
def cache_method_results(object_id = None, timeout = METHOD_RESULTS_TIMEOUT,
argument_processor = None):
''' Cache the method results in the local cache. The decorator receives an
object_id, that can be a name of a member, name of a getter (method
which does not receive any arguments other than self) or a lambda
function for generating the id of the instance. It can also be empty
in case of a singleton.
'''
from django.core.cache import get_cache
cache = get_cache('common.method_results')
def wrap(function):
def new_function(*args, **kwargs):
assert args
object = args[0]
if not object_id:
id = '_'
elif isinstance(object_id, types.FunctionType):
id = object_id(object)
elif isinstance(object_id, basestring) and hasattr(object, object_id):
id = getattr(object, object_id)
if isinstance(id, types.MethodType):
id = id()
else:
id = object_id
if len(args) == 1:
argument = ''
else:
if argument_processor:
argument = argument_processor(*args, **kwargs)
else:
assert not kwargs # must have a processor
argument = ('_'.join(map(str, args[1:]))).strip()
key = '_%s_%s_%s_%s' % (object.__class__.__name__,
id, function.__name__, argument)
if cache.has_key(key):
return cache.get(key)
else:
result = function(*args)
cache.set(key, result, timeout)
return result
return new_function
return wrap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment