Created
June 11, 2013 15:14
-
-
Save craiglabenz/5757697 to your computer and use it in GitHub Desktop.
Django < 1.6 template chunk key checker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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