开发者

In Django, how can I automatically set "cache-control" for every template render?

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 somewha开发者_运维问答t global?


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.


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/


There is a way to setup "per site" cache with django 1.2

http://docs.djangoproject.com/en/1.2/topics/cache/#the-per-site-cache


Look at the whitenoise package if you don't want to get nginx/apache doing the work for you. It automatically hashes static files then sets optimum compression and cache settings on your static files.

If you want to set it in an individual, dynamic view (does not seem like your situation but maybe for other visitors):

response = HttpResponse(template.render(context, request))
response['Cache-Control'] = f'max-age={60*60*24}'
return response
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜