Login

Per-site vary cache on language

Author:
fneumann
Posted:
October 10, 2007
Language:
Python
Version:
.96
Score:
2 (after 2 ratings)

I like the per-site caching offered by Django (it's simple) and I like the cache to be dependent on the chosen language. Unfortunately with the current CacheMiddleware you can either have the one or the other but not both at the same time.

VaryOnLangCacheMiddleware is a small wrapper around CacheMiddleware. It looks at the request.LANGUAGE_CODE (set by LocaleMiddleware) and appends it to your CACHE_MIDDLEWARE_KEY_PREFIX. So "mysiteprefix" becomes "mysiteprefix_en" or "mysiteprefix_de-AT" depending on the user's chosen language. Site-wide, so no messing with per-view decorators and stuff.

To use this, make sure VaryOnLangCacheMiddleware comes below LocaleMiddleware in your settings.py. If you haven't set your CACHE_MIDDLEWARE_KEY_PREFIX, it's works, too.

Update: Replaced super() calls with CacheMiddleware.xxx(self, ...).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from django.middleware.cache import CacheMiddleware

class VaryOnLangCacheMiddleware(CacheMiddleware):

    def __init__(self, **kwargs):
        CacheMiddleware.__init__(self, **kwargs)
        self.ori_key_prefix = self.key_prefix

    def process_request(self, request):
        # Reset key_prefix depending on language
        lang_suffix = '_%s' % request.LANGUAGE_CODE
        if not self.key_prefix.endswith(lang_suffix):
            self.key_prefix = self.ori_key_prefix + lang_suffix
        return CacheMiddleware.process_request(self, request)

More like this

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

Comments

jdunck (on October 22, 2007):

This snippet should not be necessary.

If your view's output depends on the language, just make sure that your HttpResponse has a Vary header that indicates Accept-Language.

(This is still an issue if you use the low-level cache, but not the middleware or decorators.)

Note that if you're using the LocaleMiddleware, you should put this before the CacheMiddleware in your MIDDLEWARE_CLASSES. Order of middleware is important.

If this snippet is, in fact, needed for some reason, it's likely a bug in Django. Rather than using this snippet, please report the details of the bug.

#

Please login first before commenting.