1 from django
.core
.cache
import cache
4 NOT_IN_CACHE
= object()
7 def get_cache_or_calc(key
, calc
, timeout
=None, version
=None, *args
, **kwargs
):
8 """ Gets the value from the cache or calculates it
10 If the value needs to be calculated, it is stored in the cache. """
12 value
= cache
.get(key
, NOT_IN_CACHE
, version
=version
)
14 if value
is NOT_IN_CACHE
:
15 value
= calc(*args
, **kwargs
)
16 cache
.set(key
, value
, timeout
=timeout
, version
=version
)
22 def cache_result(key
, timeout
=None, version
=None):
23 """ Decorator to cache the result of a function call
27 @cache_result('myfunc', timeout=60)
28 def my_function(a, b, c):
34 def _get(*args
, **kwargs
):
36 key
= create_key(key
, args
, kwargs
)
39 value
= cache
.get(key
, NOT_IN_CACHE
, version
=version
)
41 if value
is NOT_IN_CACHE
:
42 value
= f(*args
, **kwargs
)
44 cache
.set(key
, value
, timeout
=timeout
, version
=version
)
55 def create_key(key
, args
, kwargs
):
57 args_str
= '-'.join(hash(a
) for a
in args
)
58 kwargs_str
= '-'.join(hash(i
) for i
in kwargs
.items())
60 return '{key}-{args}-{kwargs}'.format(key
=key
, args
=hash(args_str
),
61 kwargs
=hash(kwargs_str
))