This decorator does automatic key generation and simplifies caching. Can be used with any class, not just model subclasses.
Also see Stales Cache Decorator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | from django.core.cache import cache
def cacheable(cache_key, timeout=3600):
def paramed_decorator(func):
def decorated(self):
key = cache_key % self.__dict__
res = cache.get(key)
if res == None:
res = func(self)
cache.set(key, res, timeout)
return res
decorated.__doc__ = func.__doc__
decorated.__dict__ = func.__dict__
return decorated
return paramed_decorator
# Usage:
class SomeClass(models.Model):
# fields [id, name etc]
@cacheable("SomeClass_get_some_result_%(id)s")
def get_some_result(self):
# do some heavy calculations
return heavy_calculations()
@cacheable("SomeClass_get_something_else_%(name)s")
return something_else_calculator(self)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
May be cache value is None,that the code below res = cache.get(key) if res == None:
should change to:
if not cache.has_key(key): .... else: return cache.get(key)
#
Please login first before commenting.