Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 somewhat global?

like image 620
TIMEX Avatar asked Dec 14 '10 21:12

TIMEX


1 Answers

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.

like image 77
Paulo Scardine Avatar answered Nov 02 '22 22:11

Paulo Scardine