MCPcopy Index your code
hub / github.com/django/django / FetchFromCacheMiddleware

Class FetchFromCacheMiddleware

django/middleware/cache.py:146–202  ·  view source on GitHub ↗

Request-phase cache middleware that fetches a page from the cache. Must be used as part of the two-part update/fetch cache middleware. FetchFromCacheMiddleware must be the last piece of middleware in MIDDLEWARE so that it'll get called last during the request phase.

Source from the content-addressed store, hash-verified

144
145
146class FetchFromCacheMiddleware(MiddlewareMixin):
147 """
148 Request-phase cache middleware that fetches a page from the cache.
149
150 Must be used as part of the two-part update/fetch cache middleware.
151 FetchFromCacheMiddleware must be the last piece of middleware in MIDDLEWARE
152 so that it'll get called last during the request phase.
153 """
154
155 def __init__(self, get_response):
156 super().__init__(get_response)
157 self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
158 self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
159
160 @property
161 def cache(self):
162 return caches[self.cache_alias]
163
164 def process_request(self, request):
165 """
166 Check whether the page is already cached and return the cached
167 version if available.
168 """
169 if request.method not in ("GET", "HEAD"):
170 request._cache_update_cache = False
171 return None # Don't bother checking the cache.
172
173 # try and get the cached GET response
174 cache_key = get_cache_key(request, self.key_prefix, "GET", cache=self.cache)
175 if cache_key is None:
176 request._cache_update_cache = True
177 return None # No cache information available, need to rebuild.
178 response = self.cache.get(cache_key)
179 # if it wasn't found and we are looking for a HEAD, try looking just
180 # for that
181 if response is None and request.method == "HEAD":
182 cache_key = get_cache_key(
183 request, self.key_prefix, "HEAD", cache=self.cache
184 )
185 response = self.cache.get(cache_key)
186
187 if response is None:
188 request._cache_update_cache = True
189 return None # No cache information available, need to rebuild.
190
191 # Derive the age estimation of the cached response.
192 if (max_age_seconds := get_max_age(response)) is not None and (
193 expires_timestamp := parse_http_date_safe(response["Expires"])
194 ) is not None:
195 now_timestamp = int(time.time())
196 remaining_seconds = expires_timestamp - now_timestamp
197 # Use Age: 0 if local clock got turned back.
198 response["Age"] = max(0, max_age_seconds - remaining_seconds)
199
200 # hit, return cached response
201 request._cache_update_cache = False
202 return response
203

Calls

no outgoing calls

Used in the wild real call sites across dependent graphs

searching dependent graphs…