Prerequisites:
– Python Memcahed Library
– Memcached server
Settings.py
CACHES = { 'default' : { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': ['127.0.0.1:11211'], 'KEY_PREFIX': 'YOUR_PREFIX', } }
Caching Code
from django.core.cache import cache #get the cache key for storage def cache_get_key(*args, **kwargs): import hashlib serialise = [] for arg in args: serialise.append(str(arg)) for key,arg in kwargs.items(): serialise.append(str(key)) serialise.append(str(arg)) key = hashlib.md5("".join(serialise)).hexdigest() return key #decorator for caching functions def cache_for(time): def decorator(fn): def wrapper(*args, **kwargs): key = cache_get_key(fn.__name__, *args, **kwargs) result = cache.get(key) if not result: result = fn(*args, **kwargs) cache.set(key, result, time) return result return wrapper return decorator
Usage
@cache_for(7200) def get_districts(region_slug): result = api.get_districts(region_slug) return result
A mniute saved is a minute earned, and this saved hours!
Thanks for this. I “forked” this and made some improvements, and packaged it up on PyPI.
Install with pip install django-cache-decorator
Source: https://github.com/rchrd2/django-cache-decorator