PageRenderTime 91ms CodeModel.GetById 6ms RepoModel.GetById 0ms app.codeStats 0ms

/django/middleware/cache.py

https://code.google.com/p/mango-py/
Python | 205 lines | 151 code | 12 blank | 42 comment | 21 complexity | 080e87991c5bb9630aa2a10055220a19 MD5 | raw file
Possible License(s): BSD-3-Clause
  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. * If CACHE_MIDDLEWARE_ANONYMOUS_ONLY is set to True, only anonymous requests
  26. (i.e., those not made by a logged-in user) will be cached. This is a simple
  27. and effective way of avoiding the caching of the Django admin (and any other
  28. user-specific content).
  29. * This middleware expects that a HEAD request is answered with the same response
  30. headers exactly like the corresponding GET request.
  31. * When a hit occurs, a shallow copy of the original response object is returned
  32. from process_request.
  33. * Pages will be cached based on the contents of the request headers listed in
  34. the response's "Vary" header.
  35. * This middleware also sets ETag, Last-Modified, Expires and Cache-Control
  36. headers on the response object.
  37. """
  38. from django.conf import settings
  39. from django.core.cache import get_cache, DEFAULT_CACHE_ALIAS
  40. from django.utils.cache import get_cache_key, learn_cache_key, patch_response_headers, get_max_age
  41. class UpdateCacheMiddleware(object):
  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
  47. MIDDLEWARE_CLASSES so that it'll get called last during the response phase.
  48. """
  49. def __init__(self):
  50. self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
  51. self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  52. self.cache_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False)
  53. self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
  54. self.cache = get_cache(self.cache_alias)
  55. def _session_accessed(self, request):
  56. try:
  57. return request.session.accessed
  58. except AttributeError:
  59. return False
  60. def _should_update_cache(self, request, response):
  61. if not hasattr(request, '_cache_update_cache') or not request._cache_update_cache:
  62. return False
  63. # If the session has not been accessed otherwise, we don't want to
  64. # cause it to be accessed here. If it hasn't been accessed, then the
  65. # user's logged-in status has not affected the response anyway.
  66. if self.cache_anonymous_only and self._session_accessed(request):
  67. 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."
  68. if request.user.is_authenticated():
  69. # Don't cache user-variable requests from authenticated users.
  70. return False
  71. return True
  72. def process_response(self, request, response):
  73. """Sets the cache, if needed."""
  74. if not self._should_update_cache(request, response):
  75. # We don't need to update the cache, just return.
  76. return response
  77. if not response.status_code == 200:
  78. return response
  79. # Try to get the timeout from the "max-age" section of the "Cache-
  80. # Control" header before reverting to using the default cache_timeout
  81. # length.
  82. timeout = get_max_age(response)
  83. if timeout == None:
  84. timeout = self.cache_timeout
  85. elif timeout == 0:
  86. # max-age was set to 0, don't bother caching.
  87. return response
  88. patch_response_headers(response, timeout)
  89. if timeout:
  90. cache_key = learn_cache_key(request, response, timeout, self.key_prefix, cache=self.cache)
  91. if hasattr(response, 'render') and callable(response.render):
  92. response.add_post_render_callback(
  93. lambda r: self.cache.set(cache_key, r, timeout)
  94. )
  95. else:
  96. self.cache.set(cache_key, response, timeout)
  97. return response
  98. class FetchFromCacheMiddleware(object):
  99. """
  100. Request-phase cache middleware that fetches a page from the cache.
  101. Must be used as part of the two-part update/fetch cache middleware.
  102. FetchFromCacheMiddleware must be the last piece of middleware in
  103. MIDDLEWARE_CLASSES so that it'll get called last during the request phase.
  104. """
  105. def __init__(self):
  106. self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
  107. self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  108. self.cache_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False)
  109. self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
  110. self.cache = get_cache(self.cache_alias)
  111. def process_request(self, request):
  112. """
  113. Checks whether the page is already cached and returns the cached
  114. version if available.
  115. """
  116. if not request.method in ('GET', 'HEAD'):
  117. request._cache_update_cache = False
  118. return None # Don't bother checking the cache.
  119. # try and get the cached GET response
  120. cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache)
  121. if cache_key is None:
  122. request._cache_update_cache = True
  123. return None # No cache information available, need to rebuild.
  124. response = self.cache.get(cache_key, None)
  125. # if it wasn't found and we are looking for a HEAD, try looking just for that
  126. if response is None and request.method == 'HEAD':
  127. cache_key = get_cache_key(request, self.key_prefix, 'HEAD', cache=self.cache)
  128. response = self.cache.get(cache_key, None)
  129. if response is None:
  130. request._cache_update_cache = True
  131. return None # No cache information available, need to rebuild.
  132. # hit, return cached response
  133. request._cache_update_cache = False
  134. return response
  135. class CacheMiddleware(UpdateCacheMiddleware, FetchFromCacheMiddleware):
  136. """
  137. Cache middleware that provides basic behavior for many simple sites.
  138. Also used as the hook point for the cache decorator, which is generated
  139. using the decorator-from-middleware utility.
  140. """
  141. def __init__(self, cache_timeout=None, cache_anonymous_only=None, **kwargs):
  142. # We need to differentiate between "provided, but using default value",
  143. # and "not provided". If the value is provided using a default, then
  144. # we fall back to system defaults. If it is not provided at all,
  145. # we need to use middleware defaults.
  146. cache_kwargs = {}
  147. try:
  148. self.key_prefix = kwargs['key_prefix']
  149. if self.key_prefix is not None:
  150. cache_kwargs['KEY_PREFIX'] = self.key_prefix
  151. else:
  152. self.key_prefix = ''
  153. except KeyError:
  154. self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
  155. cache_kwargs['KEY_PREFIX'] = self.key_prefix
  156. try:
  157. self.cache_alias = kwargs['cache_alias']
  158. if self.cache_alias is None:
  159. self.cache_alias = DEFAULT_CACHE_ALIAS
  160. if cache_timeout is not None:
  161. cache_kwargs['TIMEOUT'] = cache_timeout
  162. except KeyError:
  163. self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
  164. if cache_timeout is None:
  165. cache_kwargs['TIMEOUT'] = settings.CACHE_MIDDLEWARE_SECONDS
  166. else:
  167. cache_kwargs['TIMEOUT'] = cache_timeout
  168. if cache_anonymous_only is None:
  169. self.cache_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False)
  170. else:
  171. self.cache_anonymous_only = cache_anonymous_only
  172. self.cache = get_cache(self.cache_alias, **cache_kwargs)
  173. self.cache_timeout = self.cache.default_timeout