Created
November 5, 2015 18:06
-
-
Save pardo/cf9341a754dce89058e2 to your computer and use it in GitHub Desktop.
Cached Method decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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