Login

Get the Django decorator/middleware cache key for given URL

Author:
s29
Posted:
November 8, 2011
Language:
Python
Version:
1.3
Score:
2 (after 2 ratings)

This mimicks the keys used internally by the @cache_page decorators and site-wide CacheMiddleware.

Now you can poke them, prod them, delete them, do what you like with them (eg, delete after you update some content and you want a specific URL refreshed).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.