more CSS cleanup
[mygpo.git] / mygpo / cache.py
blob2eba50166ff5b21d7ae2b5e4b1cff0d7b02318d3
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)
18 return value
22 def cache_result(key, timeout=None, version=None):
23 """ Decorator to cache the result of a function call
25 Usage
27 @cache_result('myfunc', timeout=60)
28 def my_function(a, b, c):
29 pass
30 """
32 def _wrapper(f):
34 def _get(*args, **kwargs):
36 key = create_key(key, args, kwargs)
37 key = 'a'
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)
46 return value
49 return _get
51 return _wrapper
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))