Skip to content

Instantly share code, notes, and snippets.

@craiglabenz
Created June 11, 2013 15:14
Show Gist options
  • Save craiglabenz/5757697 to your computer and use it in GitHub Desktop.
Save craiglabenz/5757697 to your computer and use it in GitHub Desktop.
Django < 1.6 template chunk key checker
# standard lib
import hashlib
# django
from django.core.cache import cache
from django.utils.encoding import force_bytes
from django.utils.http import urlquote
def make_template_fragment_key(fragment_name, vary_on=[]):
'''
Mimicks Django's internal cache key generation to see if a particular
object is available in the cache.
This function will be natively supported in Django 1.6, at which time we will
abandon this use in favor of the official cache API.
'''
# Cast the variable as a list if it's not already
if not isinstance(vary_on, list):
vary_on = [vary_on]
key = ':'.join([urlquote(var) for var in vary_on])
args = hashlib.md5(force_bytes(key))
cache_key = 'template.cache.%s.%s' % (fragment_name, args.hexdigest())
return cache_key
def cache_has_key(fragment_name, vary_on=[]):
key = make_template_fragment_key(fragment_name, vary_on)
# get() returns default (False, in this case) if the key is found but expired
return cache.get(key, False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment