Python decorator – caching your django functions

By | September 8, 2011

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

2 thoughts on “Python decorator – caching your django functions

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.