Cache (memoize) a function's output using Django's caching API
MIT License
Table of Contents generated with autotoc
django_function_cache
allows you to wrap functions so they cache
their output if they are repeatedly called with the same
arguments. Assumes that functions return values that can be pickled.
$ pip install django_function_cache
Simply wrap cached
around your expensive function:
from urllib2 import urlopen
import json
from django_function_cache import cached
def get_external_ip():
response = urlopen("http://httpbin.org/ip").read()
ip = json.loads(response)['origin']
return ip
def print_my_ip():
print cached(get_external_ip)()
You can also specify a timeout:
def print_my_ip():
print cached(get_external_ip, minutes=5)()
You can specify any time units supported by timedelta.
If the wrapped function raises an exception, nothing is cached and the exception propagates as if you'd call the function directly.
If you're just caching database calls, you're probably better off using Johnny Cache.
Added Python 2.6 support. Added Travis tests to ensure we work with the range of Python versions and Django versions that we claim we do.
Changed the top level package name. Previously you would write:
from cached import cached
Now:
from django_function_cache import cached
Initial release.
Check out the code, and install it in a virtual environment that includes Django:
$ source path/to/your/virtualenv
$ pip install -e .
Hack away, then send a pull request when you're happy.
$ python setup.py sdist upload