Skip to content

Instantly share code, notes, and snippets.

@JeromeParadis
Created September 27, 2011 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeromeParadis/1245890 to your computer and use it in GitHub Desktop.
Save JeromeParadis/1245890 to your computer and use it in GitHub Desktop.
Django get or set Cache pattern
from django.core.cache import cache
# Here, you can centralize sanitation of cache key.
# There was a python memcache bug were spaces in keys were generating exceptions, so we replace it
# You could add any other code to fix keys here
def sanitize_cache_key(cache_key):
key = cache_key
if key and len(key) >0:
key = key.replace(' ','%20')
return key
# cache_key: string for the cache key
# timeout: you cache timeout
# fn: a function to execute if cache is empty and that returns data
# args: a tule of the arguments to pass to the function
def get_set_cache(cache_key,timeout,fn,args):
cache_name = sanitize_cache_key(cache_key)
content = cache.get(cache_name)
if content is None:
content = fn(*args)
if content:
cache.set(cache_name,content,timeout)
return content
# Example
def get_user_stuff(user,other_data):
cache_name = "user_%d_stuff_%d" % (user.id,other_data.id)
return get_set_cache(cache_name,60*60,_get_user_stuff,(user,other_data))
def _get_user_stuff(user,other_data):
some_data = ... # long running fetching of some data that depends on user and other_DATA
return some_data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment