- October 10, 2007
- middleware i18n cache language
- 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.
super() calls with
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
- Multilingual Models by Archatas 8 years, 2 months ago
- SQLLoggerMidleware + infobar by robvdl 7 years, 3 months ago
- Caching XHTML render_to_response by smoonen 6 years, 9 months ago
- Getting dynamic model choices in newforms by ubernostrum 8 years, 2 months ago
- language switcher in admin by lawgon 5 years, 5 months ago