Skip to content

Instantly share code, notes, and snippets.

@niwinz
Created July 4, 2012 22:39
Show Gist options
  • Save niwinz/3049907 to your computer and use it in GitHub Desktop.
Save niwinz/3049907 to your computer and use it in GitHub Desktop.
Cache decorator for view methods (django)
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment