| 1 |
from functools import wraps |
| 2 |
import itertools |
| 3 |
import json |
| 4 |
import inspect |
| 5 |
|
| 6 |
import hashlib |
| 7 |
from urllib.parse import quote |
| 8 |
|
| 9 |
from django.db import models |
| 10 |
from django.core.cache import caches, DEFAULT_CACHE_ALIAS |
| 11 |
from django.core.cache.backends.base import DEFAULT_TIMEOUT |
| 12 |
|
| 13 |
from django.utils.encoding import force_bytes |
| 14 |
|
| 15 |
MARKER = object() |
| 16 |
|
| 17 |
|
| 18 |
def cache_memoize( |
| 19 |
timeout=DEFAULT_TIMEOUT, |
| 20 |
prefix=None, |
| 21 |
extra=None, |
| 22 |
args_rewrite=None, |
| 23 |
hit_callable=None, |
| 24 |
miss_callable=None, |
| 25 |
key_generator_callable=None, |
| 26 |
store_result=True, |
| 27 |
cache_exceptions=(), |
| 28 |
cache_alias=DEFAULT_CACHE_ALIAS, |
| 29 |
): |
| 30 |
"""Decorator for memoizing function calls where we use the |
| 31 |
"local cache" to store the result. |
| 32 |
|
| 33 |
:arg int timeout: Number of seconds to store the result if not None |
| 34 |
:arg string prefix: If None becomes the function name. |
| 35 |
:arg extra: Optional callable or serializable structure of key |
| 36 |
components cache should vary on. |
| 37 |
:arg function args_rewrite: Callable that rewrites the args first useful |
| 38 |
if your function needs nontrivial types but you know a simple way to |
| 39 |
re-represent them for the sake of the cache key. |
| 40 |
:arg function hit_callable: Gets executed if key was in cache. |
| 41 |
:arg function miss_callable: Gets executed if key was *not* in cache. |
| 42 |
:arg key_generator_callable: Custom cache key name generator. |
| 43 |
:arg bool store_result: If you know the result is not important, just |
| 44 |
that the cache blocked it from running repeatedly, set this to False. |
| 45 |
:arg Exception cache_exceptions: Accepts an Exception or a tuple of |
| 46 |
Exceptions. If the cached function raises any of these exceptions is the |
| 47 |
exception cached and raised as normal. Subsequent cached calls will |
| 48 |
immediately re-raise the exception and the function will not be executed. |
| 49 |
this tuple will be cached, all other will be propagated. |
| 50 |
:arg string cache_alias: The cache alias to use; defaults to 'default'. |
| 51 |
|
| 52 |
Usage:: |
| 53 |
|
| 54 |
@cache_memoize( |
| 55 |
300, # 5 min |
| 56 |
args_rewrite=lambda user: user.email, |
| 57 |
hit_callable=lambda: print("Cache hit!"), |
| 58 |
miss_callable=lambda: print("Cache miss :("), |
| 59 |
) |
| 60 |
def hash_user_email(user): |
| 61 |
dk = hashlib.pbkdf2_hmac('sha256', user.email, b'salt', 100000) |
| 62 |
return binascii.hexlify(dk) |
| 63 |
|
| 64 |
Or, when you don't actually need the result, useful if you know it's not |
| 65 |
valuable to store the execution result:: |
| 66 |
|
| 67 |
@cache_memoize( |
| 68 |
300, # 5 min |
| 69 |
store_result=False, |
| 70 |
) |
| 71 |
def send_email(email): |
| 72 |
somelib.send(email, subject="You rock!", ...) |
| 73 |
|
| 74 |
Also, whatever you do where things get cached, you can undo that. |
| 75 |
For example:: |
| 76 |
|
| 77 |
@cache_memoize(100) |
| 78 |
def callmeonce(arg1): |
| 79 |
print(arg1) |
| 80 |
|
| 81 |
callmeonce('peter') # will print 'peter' |
| 82 |
callmeonce('peter') # nothing printed |
| 83 |
callmeonce.invalidate('peter') |
| 84 |
callmeonce('peter') # will print 'peter' |
| 85 |
|
| 86 |
Suppose you know for good reason you want to bypass the cache and |
| 87 |
really let the decorator let you through you can set one extra |
| 88 |
keyword argument called `_refresh`. For example:: |
| 89 |
|
| 90 |
@cache_memoize(100) |
| 91 |
def callmeonce(arg1): |
| 92 |
print(arg1) |
| 93 |
|
| 94 |
callmeonce('peter') # will print 'peter' |
| 95 |
callmeonce('peter') # nothing printed |
| 96 |
callmeonce('peter', _refresh=True) # will print 'peter' |
| 97 |
|
| 98 |
If your cache depends on external state you can provide `extra` values:: |
| 99 |
|
| 100 |
@cache_memoize(100, extra={'version': 2}) |
| 101 |
def callmeonce(arg1): |
| 102 |
print(arg1) |
| 103 |
|
| 104 |
An `extra` argument can be callable or any serializable structure:: |
| 105 |
|
| 106 |
@cache_memoize(100, extra=lambda req: req.user.is_staff) |
| 107 |
def callmeonce(arg1): |
| 108 |
print(arg1) |
| 109 |
""" |
| 110 |
|
| 111 |
if args_rewrite is None: |
| 112 |
|
| 113 |
def noop(*args): |
| 114 |
return args |
| 115 |
|
| 116 |
args_rewrite = noop |
| 117 |
|
| 118 |
def obj_key(obj): |
| 119 |
if isinstance(obj, models.Model): |
| 120 |
return "%s.%s.%s" % (obj._meta.app_label, obj._meta.model_name, obj.pk) |
| 121 |
elif hasattr(obj, "build_absolute_uri"): |
| 122 |
return obj.build_absolute_uri() |
| 123 |
elif inspect.isfunction(obj): |
| 124 |
factors = [obj.__module__, obj.__name__] |
| 125 |
return factors |
| 126 |
else: |
| 127 |
return str(obj) |
| 128 |
|
| 129 |
def decorator(func): |
| 130 |
def _default_make_cache_key(*args, **kwargs): |
| 131 |
cache_key = ":".join( |
| 132 |
itertools.chain( |
| 133 |
(quote(str(x)) for x in args_rewrite(*args)), |
| 134 |
( |
| 135 |
"{}={}".format(quote(k), quote(str(v))) |
| 136 |
for k, v in sorted(kwargs.items()) |
| 137 |
), |
| 138 |
) |
| 139 |
) |
| 140 |
prefix_ = prefix or ".".join((func.__module__ or "", func.__qualname__)) |
| 141 |
extra_val = json.dumps( |
| 142 |
extra(*args, **kwargs) if callable(extra) else extra, |
| 143 |
sort_keys=True, |
| 144 |
default=obj_key, |
| 145 |
) |
| 146 |
return hashlib.md5( |
| 147 |
force_bytes("cache_memoize" + prefix_ + cache_key + extra_val) |
| 148 |
).hexdigest() |
| 149 |
|
| 150 |
_make_cache_key = key_generator_callable or _default_make_cache_key |
| 151 |
|
| 152 |
@wraps(func) |
| 153 |
def inner(*args, **kwargs): |
| 154 |
# The cache backend is fetched here (not in the outer decorator scope) |
| 155 |
# to guarantee thread-safety at runtime. |
| 156 |
cache = caches[cache_alias] |
| 157 |
# The cache key string should never be dependent on special keyword |
| 158 |
# arguments like _refresh. So extract it into a variable as soon as |
| 159 |
# possible. |
| 160 |
_refresh = bool(kwargs.pop("_refresh", False)) |
| 161 |
cache_key = _make_cache_key(*args, **kwargs) |
| 162 |
if _refresh: |
| 163 |
result = MARKER |
| 164 |
else: |
| 165 |
result = cache.get(cache_key, MARKER) |
| 166 |
if result is MARKER: |
| 167 |
# If the function all raises an exception we want to cache, |
| 168 |
# catch it, else let it propagate. |
| 169 |
try: |
| 170 |
result = func(*args, **kwargs) |
| 171 |
except cache_exceptions as exception: |
| 172 |
result = exception |
| 173 |
|
| 174 |
if not store_result: |
| 175 |
# Then the result isn't valuable/important to store but |
| 176 |
# we want to store something. Just to remember that |
| 177 |
# it has be done. |
| 178 |
cache.set(cache_key, True, timeout) |
| 179 |
else: |
| 180 |
cache.set(cache_key, result, timeout) |
| 181 |
if miss_callable: |
| 182 |
miss_callable(*args, **kwargs) |
| 183 |
elif hit_callable: |
| 184 |
hit_callable(*args, **kwargs) |
| 185 |
|
| 186 |
# If the result is an exception we've caught and cached, raise it |
| 187 |
# in the end as to not change the API of the function we're caching. |
| 188 |
if isinstance(result, Exception): |
| 189 |
raise result |
| 190 |
return result |
| 191 |
|
| 192 |
def invalidate(*args, **kwargs): |
| 193 |
# The cache backend is fetched here (not in the outer decorator scope) |
| 194 |
# to guarantee thread-safety at runtime. |
| 195 |
cache = caches[cache_alias] |
| 196 |
kwargs.pop("_refresh", None) |
| 197 |
cache_key = _make_cache_key(*args, **kwargs) |
| 198 |
cache.delete(cache_key) |
| 199 |
|
| 200 |
def get_cache_key(*args, **kwargs): |
| 201 |
kwargs.pop("_refresh", None) |
| 202 |
return _make_cache_key(*args, **kwargs) |
| 203 |
|
| 204 |
inner.invalidate = invalidate |
| 205 |
inner.get_cache_key = get_cache_key |
| 206 |
return inner |
| 207 |
|
| 208 |
return decorator |