Nov 9, 2011

Django decorator/middleware cache key for given URL

import hashlib
from django.utils.encoding import iri_to_uri
from django.conf import settings
from django.utils.translation import get_language

def url_cache_key(url, language=None, key_prefix=None):
    if key_prefix is None:
        key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
    ctx = hashlib.md5()
    path = hashlib.md5(iri_to_uri(url))
    cache_key = 'views.decorators.cache.cache_page.%s.%s.%s.%s' % (
        key_prefix, 'GET', path.hexdigest(), ctx.hexdigest())
    if settings.USE_I18N:
        cache_key += '.%s' % (language or get_language())
    return cache_key


http://djangosnippets.org/snippets/2595/

No comments: