cache.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 response
  26. 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. """
  34. import time
  35. from django.conf import settings
  36. from django.core.cache import DEFAULT_CACHE_ALIAS, caches
  37. from django.utils.cache import (
  38. get_cache_key,
  39. get_max_age,
  40. has_vary_header,
  41. learn_cache_key,
  42. patch_response_headers,
  43. )
  44. from django.utils.deprecation import MiddlewareMixin
  45. from django.utils.http import parse_http_date_safe
  46. class UpdateCacheMiddleware(MiddlewareMixin):
  47. """
  48. Response-phase cache middleware that updates the cache if the response is
  49. cacheable.
  50. Must be used as part of the two-part update/fetch cache middleware.
  51. UpdateCacheMiddleware must be the first piece of middleware in MIDDLEWARE
  52. so that it'll get called last during the response phase.
  53. """
  54. def __init__(self, get_response):
  55. super().__init__(get_response)
  56. self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
  57. self.page_timeout = None
  58. self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  59. self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
  60. @property
  61. def cache(self):
  62. return caches[self.cache_alias]
  63. def _should_update_cache(self, request, response):
  64. return hasattr(request, "_cache_update_cache") and request._cache_update_cache
  65. def process_response(self, request, response):
  66. """Set the cache, if needed."""
  67. if not self._should_update_cache(request, response):
  68. # We don't need to update the cache, just return.
  69. return response
  70. if response.streaming or response.status_code not in (200, 304):
  71. return response
  72. # Don't cache responses that set a user-specific (and maybe security
  73. # sensitive) cookie in response to a cookie-less request.
  74. if (
  75. not request.COOKIES
  76. and response.cookies
  77. and has_vary_header(response, "Cookie")
  78. ):
  79. return response
  80. # Don't cache a response with 'Cache-Control: private'
  81. if "private" in response.get("Cache-Control", ()):
  82. return response
  83. # Page timeout takes precedence over the "max-age" and the default
  84. # cache timeout.
  85. timeout = self.page_timeout
  86. if timeout is None:
  87. # The timeout from the "max-age" section of the "Cache-Control"
  88. # header takes precedence over the default cache timeout.
  89. timeout = get_max_age(response)
  90. if timeout is None:
  91. timeout = self.cache_timeout
  92. elif timeout == 0:
  93. # max-age was set to 0, don't cache.
  94. return response
  95. patch_response_headers(response, timeout)
  96. if timeout and response.status_code == 200:
  97. cache_key = learn_cache_key(
  98. request, response, timeout, self.key_prefix, cache=self.cache
  99. )
  100. if hasattr(response, "render") and callable(response.render):
  101. response.add_post_render_callback(
  102. lambda r: self.cache.set(cache_key, r, timeout)
  103. )
  104. else:
  105. self.cache.set(cache_key, response, timeout)
  106. return response
  107. class FetchFromCacheMiddleware(MiddlewareMixin):
  108. """
  109. Request-phase cache middleware that fetches a page from the cache.
  110. Must be used as part of the two-part update/fetch cache middleware.
  111. FetchFromCacheMiddleware must be the last piece of middleware in MIDDLEWARE
  112. so that it'll get called last during the request phase.
  113. """
  114. def __init__(self, get_response):
  115. super().__init__(get_response)
  116. self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  117. self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
  118. @property
  119. def cache(self):
  120. return caches[self.cache_alias]
  121. def process_request(self, request):
  122. """
  123. Check whether the page is already cached and return the cached
  124. version if available.
  125. """
  126. if request.method not in ("GET", "HEAD"):
  127. request._cache_update_cache = False
  128. return None # Don't bother checking the cache.
  129. # try and get the cached GET response
  130. cache_key = get_cache_key(request, self.key_prefix, "GET", cache=self.cache)
  131. if cache_key is None:
  132. request._cache_update_cache = True
  133. return None # No cache information available, need to rebuild.
  134. response = self.cache.get(cache_key)
  135. # if it wasn't found and we are looking for a HEAD, try looking just for that
  136. if response is None and request.method == "HEAD":
  137. cache_key = get_cache_key(
  138. request, self.key_prefix, "HEAD", cache=self.cache
  139. )
  140. response = self.cache.get(cache_key)
  141. if response is None:
  142. request._cache_update_cache = True
  143. return None # No cache information available, need to rebuild.
  144. # Derive the age estimation of the cached response.
  145. if (max_age_seconds := get_max_age(response)) is not None and (
  146. expires_timestamp := parse_http_date_safe(response["Expires"])
  147. ) is not None:
  148. now_timestamp = int(time.time())
  149. remaining_seconds = expires_timestamp - now_timestamp
  150. # Use Age: 0 if local clock got turned back.
  151. response["Age"] = max(0, max_age_seconds - remaining_seconds)
  152. # hit, return cached response
  153. request._cache_update_cache = False
  154. return response
  155. class CacheMiddleware(UpdateCacheMiddleware, FetchFromCacheMiddleware):
  156. """
  157. Cache middleware that provides basic behavior for many simple sites.
  158. Also used as the hook point for the cache decorator, which is generated
  159. using the decorator-from-middleware utility.
  160. """
  161. def __init__(self, get_response, cache_timeout=None, page_timeout=None, **kwargs):
  162. super().__init__(get_response)
  163. # We need to differentiate between "provided, but using default value",
  164. # and "not provided". If the value is provided using a default, then
  165. # we fall back to system defaults. If it is not provided at all,
  166. # we need to use middleware defaults.
  167. try:
  168. key_prefix = kwargs["key_prefix"]
  169. if key_prefix is None:
  170. key_prefix = ""
  171. self.key_prefix = key_prefix
  172. except KeyError:
  173. pass
  174. try:
  175. cache_alias = kwargs["cache_alias"]
  176. if cache_alias is None:
  177. cache_alias = DEFAULT_CACHE_ALIAS
  178. self.cache_alias = cache_alias
  179. except KeyError:
  180. pass
  181. if cache_timeout is not None:
  182. self.cache_timeout = cache_timeout
  183. self.page_timeout = page_timeout