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