Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.8KB

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