In Django, how can I automatically set "cache-control" for every template render?
Solution 1
Eh... I'd be careful about this. The template is processed on each request. You don't want to just set it as cached willy-nilly; the data can (and probably will) change.
Thankfully, Django provides caching. I'm not sure if it sets the no-cache properly, but it definitely prevents repeated queries that aren't needed. This is what you'd want to use.
Read up on http://docs.djangoproject.com/en/dev/topics/cache/
Solution 2
You can write a custom middleware (untested, start with something like this and look at docs). It can save a lot of network resources for a site that gives pretty static information, like lottery results or historic stock quotes, for example.
# my_middleware.py
from django.conf import settings
# default 30 days
MAX_AGE = getattr(settings, 'CACHE_CONTROL_MAX_AGE', 2592000)
class MaxAgeMiddleware(object):
def process_response(self, request, response):
response['Cache-Control'] = 'max-age=%d' % MAX_AGE
return response
Append your middleware in settings.py MIDDLEWARE_CLASSES; middleware is like onion layers - order matters, during response phase first ones are processed last.
Set CACHE_CONTROL_MAX_AGE or any other parameter and give it a try.
Related videos on Youtube
TIMEX
Updated on May 12, 2022Comments
-
TIMEX about 2 years
I want to se the cache control to a higher number, instead of "no-store", which is the default for django.
Can I configure it in a way that's somewhat global?