Created
July 4, 2012 22:39
-
-
Save niwinz/3049907 to your computer and use it in GitHub Desktop.
Cache decorator for view methods (django)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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