Skip to content

Instantly share code, notes, and snippets.

@pardo
Created November 5, 2015 18:06
Show Gist options
  • Save pardo/cf9341a754dce89058e2 to your computer and use it in GitHub Desktop.
Save pardo/cf9341a754dce89058e2 to your computer and use it in GitHub Desktop.
Cached Method decorator
def cached_model_method(time=600, key_uses_args=False):
"""
Decorates django model methods
Use it as:
@cached_model_method(time=1200)
def functionToCache(arguments):
...
"""
#TODO review, just for playing a little!!!
def decorator(function):
@functools.wraps(function)
def wrapper(*args, **kwargs):
#args[0] should be an instance
if len(args) > 0 and args[0].id is not None:
key = "%s-%s-%s-%s-%s" % (args[0].__class__, function.__name__, args[0].id, args, kwargs)
key = hashlib.sha256(key).hexdigest()
value = cache.get(key)
if not value:
value = function(*args, **kwargs)
cache.set(key, value, time)
return value
else:
return function(*args, **kwargs)
return wrapper
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment