cache.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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_CLASSES = [
  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. import warnings
  35. from django.conf import settings
  36. from django.core.cache import caches, DEFAULT_CACHE_ALIAS
  37. from django.utils.cache import (get_cache_key, get_max_age, has_vary_header,
  38. learn_cache_key, patch_response_headers)
  39. from django.utils.deprecation import RemovedInDjango18Warning
  40. class UpdateCacheMiddleware(object):
  41. """
  42. Response-phase cache middleware that updates the cache if the response is
  43. cacheable.
  44. Must be used as part of the two-part update/fetch cache middleware.
  45. UpdateCacheMiddleware must be the first piece of middleware in
  46. MIDDLEWARE_CLASSES so that it'll get called last during the response phase.
  47. """
  48. def __init__(self):
  49. self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
  50. self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  51. self.cache_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False)
  52. self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
  53. self.cache = caches[self.cache_alias]
  54. def _session_accessed(self, request):
  55. try:
  56. return request.session.accessed
  57. except AttributeError:
  58. return False
  59. def _should_update_cache(self, request, response):
  60. if not hasattr(request, '_cache_update_cache') or not request._cache_update_cache:
  61. return False
  62. # If the session has not been accessed otherwise, we don't want to
  63. # cause it to be accessed here. If it hasn't been accessed, then the
  64. # user's logged-in status has not affected the response anyway.
  65. if self.cache_anonymous_only and self._session_accessed(request):
  66. assert hasattr(request, 'user'), "The Django cache middleware with CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.auth.middleware.AuthenticationMiddleware' before the CacheMiddleware."
  67. if request.user.is_authenticated():
  68. # Don't cache user-variable requests from authenticated users.
  69. return False
  70. return True
  71. def process_response(self, request, response):
  72. """Sets the cache, if needed."""
  73. if not self._should_update_cache(request, response):
  74. # We don't need to update the cache, just return.
  75. return response
  76. if response.streaming or response.status_code != 200:
  77. return response
  78. # Don't cache responses that set a user-specific (and maybe security
  79. # sensitive) cookie in response to a cookie-less request.
  80. if not request.COOKIES and response.cookies and has_vary_header(response, 'Cookie'):
  81. return response
  82. # Try to get the timeout from the "max-age" section of the "Cache-
  83. # Control" header before reverting to using the default cache_timeout
  84. # length.
  85. timeout = get_max_age(response)
  86. if timeout is None:
  87. timeout = self.cache_timeout
  88. elif timeout == 0:
  89. # max-age was set to 0, don't bother caching.
  90. return response
  91. patch_response_headers(response, timeout)
  92. if timeout:
  93. cache_key = learn_cache_key(request, response, timeout, self.key_prefix, cache=self.cache)
  94. if hasattr(response, 'render') and callable(response.render):
  95. response.add_post_render_callback(
  96. lambda r: self.cache.set(cache_key, r, timeout)
  97. )
  98. else:
  99. self.cache.set(cache_key, response, timeout)
  100. return response
  101. class FetchFromCacheMiddleware(object):
  102. """
  103. Request-phase cache middleware that fetches a page from the cache.
  104. Must be used as part of the two-part update/fetch cache middleware.
  105. FetchFromCacheMiddleware must be the last piece of middleware in
  106. MIDDLEWARE_CLASSES so that it'll get called last during the request phase.
  107. """
  108. def __init__(self):
  109. self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  110. self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
  111. self.cache = caches[self.cache_alias]
  112. def process_request(self, request):
  113. """
  114. Checks whether the page is already cached and returns the cached
  115. version if available.
  116. """
  117. if request.method not in ('GET', 'HEAD'):
  118. request._cache_update_cache = False
  119. return None # Don't bother checking the cache.
  120. # try and get the cached GET response
  121. cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache)
  122. if cache_key is None:
  123. request._cache_update_cache = True
  124. return None # No cache information available, need to rebuild.
  125. response = self.cache.get(cache_key, None)
  126. # if it wasn't found and we are looking for a HEAD, try looking just for that
  127. if response is None and request.method == 'HEAD':
  128. cache_key = get_cache_key(request, self.key_prefix, 'HEAD', cache=self.cache)
  129. response = self.cache.get(cache_key, None)
  130. if response is None:
  131. request._cache_update_cache = True
  132. return None # No cache information available, need to rebuild.
  133. # hit, return cached response
  134. request._cache_update_cache = False
  135. return response
  136. class CacheMiddleware(UpdateCacheMiddleware, FetchFromCacheMiddleware):
  137. """
  138. Cache middleware that provides basic behavior for many simple sites.
  139. Also used as the hook point for the cache decorator, which is generated
  140. using the decorator-from-middleware utility.
  141. """
  142. def __init__(self, cache_timeout=None, cache_anonymous_only=None, **kwargs):
  143. # We need to differentiate between "provided, but using default value",
  144. # and "not provided". If the value is provided using a default, then
  145. # we fall back to system defaults. If it is not provided at all,
  146. # we need to use middleware defaults.
  147. try:
  148. key_prefix = kwargs['key_prefix']
  149. if key_prefix is None:
  150. key_prefix = ''
  151. except KeyError:
  152. key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  153. self.key_prefix = key_prefix
  154. try:
  155. cache_alias = kwargs['cache_alias']
  156. if cache_alias is None:
  157. cache_alias = DEFAULT_CACHE_ALIAS
  158. except KeyError:
  159. cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
  160. self.cache_alias = cache_alias
  161. if cache_timeout is None:
  162. cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
  163. self.cache_timeout = cache_timeout
  164. if cache_anonymous_only is None:
  165. cache_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False)
  166. self.cache_anonymous_only = cache_anonymous_only
  167. if self.cache_anonymous_only:
  168. msg = "CACHE_MIDDLEWARE_ANONYMOUS_ONLY has been deprecated and will be removed in Django 1.8."
  169. warnings.warn(msg, RemovedInDjango18Warning, stacklevel=1)
  170. self.cache = caches[self.cache_alias]