[Solved]-Django cache framework. What is the difference between TIMEOUT and CACHE_MIDDLEWARE_SECONDS?


Indeed the respective documentation does not adequately explain the differences.

The first option, CACHES: TIMEOUT is introduced in Django cache framework, Cache arguments. It is the default expiration time that is used in functions such as cache.set(), if none else is provided. This is later documented in the low-level cache API usage.

The latter, CACHE_MIDDLEWARE_SECONDS is introduced in Django cache framework, The per-site cache. Therefore it might be safe to assume that it is the default expiration time for all pages, as if the @cache_page(settings.CACHE_MIDDLEWARE_SECONDS) would have been used on a per-view basis.



I had the same question and the existing answers still didn’t clear it up for me. So I decided to dive into the source code. Yay for open source!

CACHE_MIDDLEWARE_SECONDS gets used by the UpdateCacheMiddleware middleware. It sets the Cache-Control (max-age) header to the value of CACHE_MIDDLEWARE_SECONDS if the view didn’t already set it, affecting the client-side cache. Here’s the code:

    self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
    # ...
    timeout = get_max_age(response)
    if timeout is None:
        timeout = self.cache_timeout
    patch_response_headers(response, timeout)

(Note that I’m cutting out some code and edge-corners to make this quicker to read, you can read the full source code yourself of course.)

It also saves the response in the server-side cache, using the same timeout value which originates from MIDDLEWARE_CACHE_SECONDS, overriding the TIMEOUT setting if it had been set: (context)

    if timeout:
        cache_key = learn_cache_key(request, response, timeout, self.key_prefix, cache=self.cache)
        self.cache.set(cache_key, response, timeout) 

The middleware FetchFromCacheMiddleware goes with UpdateCacheMiddleware, and it uses the server-side cache values set by the latter, so it is indirectly affected by CACHE_MIDDLEWARE_SECONDS.

The alternative middleware CacheMiddleware also uses CACHE_MIDDLEWARE_SECONDS. This shouldn’t affect you unless you’re using CacheMiddleware.

So what’s the point of the TIMEOUT setting? I suppose it’s the default value that’s used if you’re writing to the cache directly, but it isn’t used by the previously mentioned middleware. For example:

from django.core.cache import cache
cache.set('my_key', 'my_value') # uses TIMEOUT value as default


According to http://www.djangobook.com/en/2.0/chapter15.html, TIMEOUT is the timeout for connecting to the cache backend and CACHE_MIDDLEWARE_SECONDS is the number of seconds to cache a page. So TIMEOUT is not necessarily useful for all backends.

Leave a comment