Search code examples
djangohttp-caching

Django's default behaviour for web/http caching


My question is referring to this section of the django docs.

In there, there is a paragraph that reads:

Note that the caching middleware already sets the cache header's max-age with the value of the CACHE_MIDDLEWARE_SECONDS setting. If you use a custom max_age in a cache_control decorator, the decorator will take precedence, and the header values will be merged correctly.

My interpretation is that, by default, responses from django server-end would have "Cache-Control:max-age=600" in their http header sections, unless some http-cache-related decorator is used to modify the "Cache-Control" header.

I performed a quick experiment to verify my interpretation above. Surprisingly, when no http-cache-related is used on the view, the response generated has NO "Cache-Control" header at all.

Why am I seeing a different result from what the official docs describes? Have I misunderstood the outlined paragraph?

Also, when there is no "Cache-Control" header in a response, can I safely assume there's no http caching involved (ie. no cached response would be used)?


Solution

  • This does not happen "by default". Two conditions must be met for Django to attach the Cache-Control header:

    1. You must have a caching backend set up, with either CACHES (Django 1.3+) or BACKEND (Django <1.3).

    2. You must add the cache middleware to MIDDLEWARE_CLASSES.

    See the docs for details.

    As far as caching in the absence of a Cache-Control header, that then becomes the decision of the web browser or client in general. Cache-Control gives directives that must be followed, but browsers already generally cache on their own, so its real purpose is usually to prevent caching in certain scenarios, rather than enabling it.