module documentation

Cache middleware. If enabled, each Django-powered page will be cached based on URL. The canonical way to enable cache middleware is to set UpdateCacheMiddleware as your first piece of middleware, and FetchFromCacheMiddleware as the last:

MIDDLEWARE = [
    'django.middleware.cache.UpdateCacheMiddleware',
    ...
    'django.middleware.cache.FetchFromCacheMiddleware'
]

This is counter-intuitive, but correct: UpdateCacheMiddleware needs to run last during the response phase, which processes middleware bottom-up; FetchFromCacheMiddleware needs to run last during the request phase, which processes middleware top-down.

The single-class CacheMiddleware can be used for some simple sites. However, if any other piece of middleware needs to affect the cache key, you'll need to use the two-part UpdateCacheMiddleware and FetchFromCacheMiddleware. This'll most often happen when you're using Django's LocaleMiddleware.

More details about how the caching works:

  • Only GET or HEAD-requests with status code 200 are cached.
  • The number of seconds each page is stored for is set by the "max-age" section of the response's "Cache-Control" header, falling back to the CACHE_MIDDLEWARE_SECONDS setting if the section was not found.
  • This middleware expects that a HEAD request is answered with the same response headers exactly like the corresponding GET request.
  • When a hit occurs, a shallow copy of the original response object is returned from process_request.
  • Pages will be cached based on the contents of the request headers listed in the response's "Vary" header.
  • This middleware also sets ETag, Last-Modified, Expires and Cache-Control headers on the response object.
Class ​Fetch​From​Cache​Middleware Request-phase cache middleware that fetches a page from the cache.
Class ​Update​Cache​Middleware Response-phase cache middleware that updates the cache if the response is cacheable.
Class ​Cache​Middleware Cache middleware that provides basic behavior for many simple sites.