- Author:
- amitu
- Posted:
- October 13, 2008
- Language:
- Python
- Version:
- 1.0
- Tags:
- cache decorator
- Score:
- 4 (after 4 ratings)
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
- Serialize a model instance by chriswedgwood 1 week, 5 days ago
- Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 9 months, 2 weeks ago
- Crispy Form by sourabhsinha396 10 months, 1 week ago
- ReadOnlySelect by mkoistinen 10 months, 2 weeks ago
- Verify events sent to your webhook endpoints by santos22 11 months, 2 weeks 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.