Created
November 12, 2013 16:48
-
-
Save orymate/7434337 to your computer and use it in GitHub Desktop.
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 method_cache(seconds=0): | |
""" | |
A `seconds` value of `0` means that we will not memcache it. | |
If a result is cached on instance, return that first. If that fails, check | |
memcached. If all else fails, run the method and cache on instance and in | |
memcached. | |
** NOTE: Methods that return None are always "recached". | |
Based on https://djangosnippets.org/snippets/2477/ | |
""" | |
def inner_cache(method): | |
def x(instance, *args, **kwargs): | |
key = sha224(unicode(method.__module__) + | |
unicode(method.__name__) + | |
unicode(instance.id) + | |
unicode(args) + | |
unicode(kwargs)).hexdigest() | |
now = time() | |
if getattr(instance, key, {'time': 0})['time'] + seconds > now: | |
# has valid on class cache, return that | |
result = getattr(instance, key)['value'] | |
else: | |
result = cache.get(key) | |
if result is None: | |
# all caches failed, call the actual method | |
result = method(instance, *args, **kwargs) | |
# save to memcache and class attr | |
if seconds and isinstance(seconds, int): | |
cache.set(key, result, seconds) | |
setattr(instance, key, {'time': now, 'value': result}) | |
return result | |
return x | |
return inner_cache |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment