Created
April 22, 2018 20:41
-
-
Save andreif/b9b30ae3d913bada171d893b16ad962c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| # coding=utf-8 | |
| from __future__ import absolute_import | |
| import time | |
| from functools import wraps | |
| from django.core.cache import cache | |
| def cached(func=None, ttl=60): | |
| def decorator(func): | |
| def _get_key(*args, **kwargs): | |
| import hashlib | |
| serialise = [] | |
| for arg in args: | |
| serialise.append(str(arg)) | |
| for k, v in sorted(kwargs.items()): | |
| serialise.append(str(k)) | |
| serialise.append(str(v)) | |
| key = hashlib.md5('-|-'.join(serialise)).hexdigest() | |
| return 'cached_%s_%s' % (func.__name__, key) | |
| def _set(key, value): | |
| cache.set(key, (value, time.time()), ttl) | |
| @wraps(func) | |
| def wrapper(*args, **kwargs): | |
| key = _get_key(*args, **kwargs) | |
| value = func(*args, **kwargs) | |
| _set(key, value) | |
| return value | |
| def cached(*args, **kwargs): | |
| key = _get_key(*args, **kwargs) | |
| value = cache.get(key) | |
| if value is None: | |
| value = func(*args, **kwargs) | |
| _set(key, value) | |
| else: | |
| value = value[0] | |
| return value | |
| def cached_time(*args, **kwargs): | |
| key = _get_key(*args, **kwargs) | |
| value = cache.get(key) | |
| if value: | |
| return cache.get(key)[1] | |
| wrapper.cached = cached | |
| wrapper.cached_time = cached_time | |
| return wrapper | |
| if func: | |
| return decorator(func=func) | |
| return decorator |
This file contains hidden or 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
| @cached(ttl=60 * 15) | |
| def some_func(a): | |
| pass | |
| some_func.cached(a=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment