Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cache.py 7.5KB

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