cache.py 8.0 KB

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