cache.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. """
  2. Cache middleware. If enabled, each Django-powered page will be cached based on
  3. URL. The canonical way to enable cache middleware is to set
  4. ``UpdateCacheMiddleware`` as your first piece of middleware, and
  5. ``FetchFromCacheMiddleware`` as the last::
  6. MIDDLEWARE = [
  7. 'django.middleware.cache.UpdateCacheMiddleware',
  8. ...
  9. 'django.middleware.cache.FetchFromCacheMiddleware'
  10. ]
  11. This is counterintuitive, but correct: ``UpdateCacheMiddleware`` needs to run
  12. last during the response phase, which processes middleware bottom-up;
  13. ``FetchFromCacheMiddleware`` needs to run last during the request phase, which
  14. processes middleware top-down.
  15. The single-class ``CacheMiddleware`` can be used for some simple sites.
  16. However, if any other piece of middleware needs to affect the cache key, you'll
  17. need to use the two-part ``UpdateCacheMiddleware`` and
  18. ``FetchFromCacheMiddleware``. This'll most often happen when you're using
  19. Django's ``LocaleMiddleware``.
  20. More details about how the caching works:
  21. * Only GET or HEAD-requests with status code 200 are cached.
  22. * The number of seconds each page is stored for is set by the "max-age" section
  23. of the response's "Cache-Control" header, falling back to the
  24. CACHE_MIDDLEWARE_SECONDS setting if the section was not found.
  25. * This middleware expects that a HEAD request is answered with the same
  26. response headers exactly like the corresponding GET request.
  27. * When a hit occurs, a shallow copy of the original response object is returned
  28. from process_request.
  29. * Pages will be cached based on the contents of the request headers listed in
  30. the response's "Vary" header.
  31. * This middleware also sets ETag, Last-Modified, Expires and Cache-Control
  32. headers on the response object.
  33. * If the request had an Authorization header and the response was not marked
  34. "Cache-Control: public", the response will vary on Authorization.
  35. """
  36. import time
  37. from django.conf import settings
  38. from django.core.cache import DEFAULT_CACHE_ALIAS, caches
  39. from django.utils.cache import (
  40. get_cache_key,
  41. get_max_age,
  42. has_vary_header,
  43. learn_cache_key,
  44. patch_response_headers,
  45. patch_vary_headers,
  46. )
  47. from django.utils.deprecation import MiddlewareMixin
  48. from django.utils.http import parse_http_date_safe, split_directive_names
  49. class UpdateCacheMiddleware(MiddlewareMixin):
  50. """
  51. Response-phase cache middleware that updates the cache if the response is
  52. cacheable.
  53. Must be used as part of the two-part update/fetch cache middleware.
  54. UpdateCacheMiddleware must be the first piece of middleware in MIDDLEWARE
  55. so that it'll get called last during the response phase.
  56. """
  57. def __init__(self, get_response):
  58. super().__init__(get_response)
  59. self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
  60. self.page_timeout = None
  61. self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  62. self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
  63. @property
  64. def cache(self):
  65. return caches[self.cache_alias]
  66. def _should_update_cache(self, request, response):
  67. return hasattr(request, "_cache_update_cache") and request._cache_update_cache
  68. def process_response(self, request, response):
  69. """Set the cache, if needed."""
  70. if not self._should_update_cache(request, response):
  71. # We don't need to update the cache, just return.
  72. return response
  73. if response.streaming or response.status_code not in (200, 304):
  74. return response
  75. # Don't cache responses that set a user-specific (and maybe security
  76. # sensitive) cookie while varying on Cookie.
  77. if response.cookies and has_vary_header(response, "Cookie"):
  78. return response
  79. # Don't cache responses when the Cache-Control header is set to
  80. # private, no-cache, or no-store. Qualified forms like
  81. # `private="Set-Cookie"` reduce to their directive name and match too.
  82. cache_control_parts = set(
  83. split_directive_names(response.get("Cache-Control", ""))
  84. )
  85. if cache_control_parts.intersection({"private", "no-cache", "no-store"}):
  86. return response
  87. # Don't cache responses when the Vary header contains '*'.
  88. if has_vary_header(response, "*"):
  89. return response
  90. # Page timeout takes precedence over the "max-age" and the default
  91. # cache timeout.
  92. timeout = self.page_timeout
  93. if timeout is None:
  94. # The timeout from the "max-age" section of the "Cache-Control"
  95. # header takes precedence over the default cache timeout.
  96. timeout = get_max_age(response)
  97. if timeout is None:
  98. timeout = self.cache_timeout
  99. elif timeout == 0:
  100. # max-age was set to 0, don't cache.
  101. return response
  102. patch_response_headers(response, timeout)
  103. # Make the response vary on Authorization if the request bears that
  104. # header, unless allowed by "public" per RFC 9111, Section 3.5. No
  105. # exceptions are made for "s-maxage" and "must-revalidate" since these
  106. # are not currently implemented by Django.
  107. if request.headers.get("Authorization") and "public" not in cache_control_parts:
  108. patch_vary_headers(response, ("Authorization",))
  109. if timeout and response.status_code == 200:
  110. cache_key = learn_cache_key(
  111. request, response, timeout, self.key_prefix, cache=self.cache
  112. )
  113. if hasattr(response, "render") and callable(response.render):
  114. response.add_post_render_callback(
  115. lambda r: self.cache.set(cache_key, r, timeout)
  116. )
  117. else:
  118. self.cache.set(cache_key, response, timeout)
  119. return response
  120. class FetchFromCacheMiddleware(MiddlewareMixin):
  121. """
  122. Request-phase cache middleware that fetches a page from the cache.
  123. Must be used as part of the two-part update/fetch cache middleware.
  124. FetchFromCacheMiddleware must be the last piece of middleware in MIDDLEWARE
  125. so that it'll get called last during the request phase.
  126. """
  127. def __init__(self, get_response):
  128. super().__init__(get_response)
  129. self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  130. self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
  131. @property
  132. def cache(self):
  133. return caches[self.cache_alias]
  134. def process_request(self, request):
  135. """
  136. Check whether the page is already cached and return the cached
  137. version if available.
  138. """
  139. if request.method not in ("GET", "HEAD"):
  140. request._cache_update_cache = False
  141. return None # Don't bother checking the cache.
  142. # try and get the cached GET response
  143. cache_key = get_cache_key(request, self.key_prefix, "GET", cache=self.cache)
  144. if cache_key is None:
  145. request._cache_update_cache = True
  146. return None # No cache information available, need to rebuild.
  147. response = self.cache.get(cache_key)
  148. # if it wasn't found and we are looking for a HEAD, try looking just
  149. # for that
  150. if response is None and request.method == "HEAD":
  151. cache_key = get_cache_key(
  152. request, self.key_prefix, "HEAD", cache=self.cache
  153. )
  154. response = self.cache.get(cache_key)
  155. if response is None:
  156. request._cache_update_cache = True
  157. return None # No cache information available, need to rebuild.
  158. # Derive the age estimation of the cached response.
  159. if (max_age_seconds := get_max_age(response)) is not None and (
  160. expires_timestamp := parse_http_date_safe(response["Expires"])
  161. ) is not None:
  162. now_timestamp = int(time.time())
  163. remaining_seconds = expires_timestamp - now_timestamp
  164. # Use Age: 0 if local clock got turned back.
  165. response["Age"] = max(0, max_age_seconds - remaining_seconds)
  166. # hit, return cached response
  167. request._cache_update_cache = False
  168. return response
  169. class CacheMiddleware(UpdateCacheMiddleware, FetchFromCacheMiddleware):
  170. """
  171. Cache middleware that provides basic behavior for many simple sites.
  172. Also used as the hook point for the cache decorator, which is generated
  173. using the decorator-from-middleware utility.
  174. """
  175. def __init__(self, get_response, cache_timeout=None, page_timeout=None, **kwargs):
  176. super().__init__(get_response)
  177. # We need to differentiate between "provided, but using default value",
  178. # and "not provided". If the value is provided using a default, then
  179. # we fall back to system defaults. If it is not provided at all,
  180. # we need to use middleware defaults.
  181. try:
  182. key_prefix = kwargs["key_prefix"]
  183. if key_prefix is None:
  184. key_prefix = ""
  185. self.key_prefix = key_prefix
  186. except KeyError:
  187. pass
  188. try:
  189. cache_alias = kwargs["cache_alias"]
  190. if cache_alias is None:
  191. cache_alias = DEFAULT_CACHE_ALIAS
  192. self.cache_alias = cache_alias
  193. except KeyError:
  194. pass
  195. if cache_timeout is not None:
  196. self.cache_timeout = cache_timeout
  197. self.page_timeout = page_timeout