Created
April 17, 2012 17:03
-
-
Save perrygeo/2407506 to your computer and use it in GitHub Desktop.
cache arbitrary functions in 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 as _djcache | |
def cache_function(seconds=6000): | |
""" | |
Cache the result of a function call for the specified number of seconds, | |
using Django's caching mechanism. | |
Assumes that the function never returns None (as the cache returns None to indicate a miss), | |
and that the function's result only depends on its parameters. | |
Note that the ordering of parameters is important. | |
e.g. myFunction(x = 1, y = 2), myFunction(y = 2, x = 1), and myFunction(1,2) will each be cached separately. | |
Usage: | |
@cache_function(600) | |
def myExpensiveMethod(parm1, parm2, parm3): | |
.... | |
return expensiveResult | |
""" | |
def doCache(f): | |
def x(*args, **kwargs): | |
key = sha1(str(f.__module__) + str(f.__name__) + str(args) + str(kwargs)).hexdigest() | |
result = _djcache.get(key) | |
if result is None: | |
result = f(*args, **kwargs) | |
_djcache.set(key, result, seconds) | |
return result | |
return x | |
return doCache |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment