Login

Per-site vary cache on language

Author:
fneumann
Posted:
October 10, 2007
Language:
Python
Version:
.96
Tags:
middleware i18n cache language
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. Multilingual Models by Archatas 8 years, 4 months ago
  2. SQLLoggerMidleware + infobar by robvdl 7 years, 5 months ago
  3. Caching XHTML render_to_response by smoonen 6 years, 11 months ago
  4. Getting dynamic model choices in newforms by ubernostrum 8 years, 4 months ago
  5. language switcher in admin by lawgon 5 years, 7 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.