淺談Django 頁面緩存的cache_key是如何生成的
頁面緩存
e.g.
@cache_page(time_out, key_prefix=key_prefix) def my_view(): ...
默認(rèn)情況下,將使用配置中的default cache
cache_page 裝飾器是由緩存中間件 CacheMiddleware 轉(zhuǎn)換而來的
CacheMiddleware 繼承了 UpdateCacheMiddleware 和 FetchFromCacheMiddleware
UpdateCacheMiddleware 繼承自 MiddlewareMixin ,只重寫了 process_response 方法,用于在處理完視圖之后將視圖緩存起來
class UpdateCacheMiddleware(MiddlewareMixin): def process_response(self, request, response): """Sets the cache, if needed.""" ... if timeout and response.status_code == 200: # 根據(jù)請求和響應(yīng)參數(shù)、設(shè)定的key_prefix生成頁面緩存的key cache_key = learn_cache_key(request, response, timeout, self.key_prefix, cache=self.cache) self.cache.set(cache_key, response, timeout) return response
FetchFromCacheMiddleware 繼承自 MiddlewareMixin ,只重寫了 process_request 方法,用于獲取當(dāng)前視圖的緩存
# django/middleware/cache.py
class FetchFromCacheMiddleware(MiddlewareMixin):
def process_request(self, request):
"""
Checks whether the page is already cached and returns the cached
version if available.
"""
# 只對方法為 GET 或 HEAD 的請求獲取緩存
if request.method not in ('GET', 'HEAD'):
request._cache_update_cache = False
return None # Don't bother checking the cache.
# try and get the cached GET response
# 這里會根據(jù)請求的信息、緩存鍵前綴生成一個cache_key。默認(rèn)情況下,訪問同一個接口其cache_key應(yīng)該相同
cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache)
if cache_key is None:
request._cache_update_cache = True
return None # No cache information available, need to rebuild.
# 如果獲取到response,則直接返回緩存的response,那么實際的視圖就不會被執(zhí)行
response = self.cache.get(cache_key)
# if it wasn't found and we are looking for a HEAD, try looking just for that
if response is None and request.method == 'HEAD':
cache_key = get_cache_key(request, self.key_prefix, 'HEAD', cache=self.cache)
response = self.cache.get(cache_key)
if response is None:
# 如果沒有獲取到緩存,將返回None,則會執(zhí)行到實際的視圖,并且重建緩存
request._cache_update_cache = True
return None # No cache information available, need to rebuild.
# hit, return cached response
request._cache_update_cache = False
return response
頁面緩存的cache_key
這一節(jié)將回答兩個問題:
- 為什么在redis中,一個頁面會保存兩個key:cache_key以及cache_header?
- 頁面緩存是如何被唯一標(biāo)識的?當(dāng)請求頭不同的時候(比如換了一個用戶請求相同的頁面)會使用同一個緩存嗎?
我們先從保存緩存視圖過程中的learn_cache_key開始
# django/utils/cache.py
def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None):
# 見下文,這個cache_key由 request的完整url 以及 key_prefix 唯一確定
cache_key = _generate_cache_header_key(key_prefix, request)
if cache is None:
# cache 是一個緩存實例
cache = caches[settings.CACHE_MIDDLEWARE_ALIAS]
# Vary 是一個HTTP響應(yīng)頭字段。其內(nèi)容是一個或多個http頭部名稱
# 比如 `Vary: User-Agent` 表示此響應(yīng)根據(jù)請求頭 `User-Agent` 的值有所不同
# 只有當(dāng)下一個請求的 `User-Agent` 值與當(dāng)前請求相同時,才會使用當(dāng)前響應(yīng)的緩存
if response.has_header('Vary'):
headerlist = []
for header in cc_delim_re.split(response['Vary']):
# 將 Vary 中出現(xiàn)的 http頭部名稱 加到 headerlist 中去
header = header.upper().replace('-', '_')
headerlist.append('HTTP_' + header)
headerlist.sort()
# 當(dāng)前 cache_key 實際上是 cache_header_key,它存的是響應(yīng)頭中Vary字段的值
cache.set(cache_key, headerlist, cache_timeout)
# 這里返回的才是頁面內(nèi)容對應(yīng)的 cache_key,它由
# 出現(xiàn)在Vary字段中的request請求頭字段的值(有序拼在一起)、request的完整url、request的method、key_prefix 唯一確定
return _generate_cache_key(request, request.method, headerlist, key_prefix)
else:
# if there is no Vary header, we still need a cache key
# for the request.build_absolute_uri()
cache.set(cache_key, [], cache_timeout)
return _generate_cache_key(request, request.method, [], key_prefix)
def _generate_cache_header_key(key_prefix, request):
"""Returns a cache key for the header cache."""
# request.build_absolute_uri()返回的是完整的請求URL。如 http://127.0.0.1:8000/api/leaflet/filterList?a=1
# 因此,請求同一個接口,但是接口參數(shù)不同,會生成兩個cache_key
url = hashlib.md5(force_bytes(iri_to_uri(request.build_absolute_uri())))
cache_key = 'views.decorators.cache.cache_header.%s.%s' % (
key_prefix, url.hexdigest())
return _i18n_cache_key_suffix(request, cache_key)
def _generate_cache_key(request, method, headerlist, key_prefix):
"""Returns a cache key from the headers given in the header list."""
ctx = hashlib.md5()
# headerlist是響應(yīng)頭中Vary字段的值
for header in headerlist:
# 出現(xiàn)在Vary字段中的request請求頭字段的值
value = request.META.get(header)
if value is not None:
ctx.update(force_bytes(value))
url = hashlib.md5(force_bytes(iri_to_uri(request.build_absolute_uri())))
cache_key = 'views.decorators.cache.cache_page.%s.%s.%s.%s' % (
key_prefix, method, url.hexdigest(), ctx.hexdigest())
return _i18n_cache_key_suffix(request, cache_key)
再看獲取緩存的get_cache_key方法
def get_cache_key(request, key_prefix=None, method='GET', cache=None):
# 由 request的完整url 以及 key_prefix 生成 cache_header_key
cache_key = _generate_cache_header_key(key_prefix, request)
# headerlist是之前緩存的 與當(dāng)前請求具有相同cache_header_key 的請求的響應(yīng)的響應(yīng)頭中Vary字段的值
headerlist = cache.get(cache_key)
# 即使響應(yīng)頭沒有Vary字段,還是會針對當(dāng)前 cache_header_key 存一個空數(shù)組
# 因此如果headerlist為None,表示當(dāng)前請求沒有緩存
if headerlist is not None:
# 根據(jù) 出現(xiàn)在Vary字段中的request請求頭字段的值(有序拼在一起)、request的完整url、request的method、key_prefix 生成 cache_key
return _generate_cache_key(request, method, headerlist, key_prefix)
else:
return None
綜上所述:
- cache_header中存的是響應(yīng)頭Vary字段的值,cache_key存的是緩存視圖
- cache_key由 出現(xiàn)在Vary字段中的request請求頭字段的值(有序拼在一起)、request的完整url、request的method、key_prefix 唯一確定
- 當(dāng)請求頭不同的時候,有可能會使用同一個緩存,這取決于不同的請求頭字段名是否出現(xiàn)在響應(yīng)頭Vary字段中。比如,如果響應(yīng)頭中有 Vary: User-Agent ,那么 User-Agent 不同的兩個請求必然生成不同的 cache_key,因此就不會使用同一個緩存。但如果只是在請求頭加一個 cache-control: no-cache (瀏覽器提供的Disable cache功能),訪問同樣的url,那還是會命中之前的緩存的
到此這篇關(guān)于淺談Django 頁面緩存的cache_key是如何生成的的文章就介紹到這了,更多相關(guān)Django cache_key頁面緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python使用正則表達(dá)式獲取網(wǎng)頁中所需要的信息
這篇文章主要介紹了Python使用正則獲取網(wǎng)頁中所需要的信息的相關(guān)資料,需要的朋友可以參考下2018-01-01
用python實現(xiàn)各種數(shù)據(jù)結(jié)構(gòu)
這篇文章主要分享的是用python實現(xiàn)各種數(shù)據(jù)結(jié)構(gòu),快速排序、選擇排序、插入排序、歸并排序、堆排序heapq模塊等相關(guān)資料,感興趣的小伙伴可以參考一下2021-12-12
Python通過30秒就能學(xué)會的漂亮短程序代碼(過程全解)
這篇文章主要介紹了Python之30秒就能學(xué)會的漂亮短程序代碼,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-10-10
Python unittest discover批量執(zhí)行代碼實例
這篇文章主要介紹了Python unittest discover批量執(zhí)行代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09
Pandas中df.loc[]與df.iloc[]的用法與異同?
本文主要介紹了Pandas中df.loc[]與df.iloc[]的用法與異同,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧?2022-07-07
Python+OpenCV實戰(zhàn)之拖拽虛擬方塊的實現(xiàn)
這篇文章主要介紹了如何利用Python+OpenCV實現(xiàn)拖拽虛擬方塊的效果,即根據(jù)手指坐標(biāo)位置和矩形的坐標(biāo)位置,判斷手指點是否在矩形上,如果在則矩形跟隨手指移動,感興趣的可以了解一下2022-08-08
pandas進(jìn)行時間數(shù)據(jù)的轉(zhuǎn)換和計算時間差并提取年月日
這篇文章主要介紹了pandas進(jìn)行時間數(shù)據(jù)的轉(zhuǎn)換和計算時間差并提取年月日,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07

