淺談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. """ # 只對(duì)方法為 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 # 這里會(huì)根據(jù)請求的信息、緩存鍵前綴生成一個(gè)cache_key。默認(rèn)情況下,訪問同一個(gè)接口其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,那么實(shí)際的視圖就不會(huì)被執(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,則會(huì)執(zhí)行到實(shí)際的視圖,并且重建緩存 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é)將回答兩個(gè)問題:
- 為什么在redis中,一個(gè)頁面會(huì)保存兩個(gè)key:cache_key以及cache_header?
- 頁面緩存是如何被唯一標(biāo)識(shí)的?當(dāng)請求頭不同的時(shí)候(比如換了一個(gè)用戶請求相同的頁面)會(huì)使用同一個(gè)緩存嗎?
我們先從保存緩存視圖過程中的learn_cache_key開始
# django/utils/cache.py def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None): # 見下文,這個(gè)cache_key由 request的完整url 以及 key_prefix 唯一確定 cache_key = _generate_cache_header_key(key_prefix, request) if cache is None: # cache 是一個(gè)緩存實(shí)例 cache = caches[settings.CACHE_MIDDLEWARE_ALIAS] # Vary 是一個(gè)HTTP響應(yīng)頭字段。其內(nèi)容是一個(gè)或多個(gè)http頭部名稱 # 比如 `Vary: User-Agent` 表示此響應(yīng)根據(jù)請求頭 `User-Agent` 的值有所不同 # 只有當(dāng)下一個(gè)請求的 `User-Agent` 值與當(dāng)前請求相同時(shí),才會(huì)使用當(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 實(shí)際上是 cache_header_key,它存的是響應(yīng)頭中Vary字段的值 cache.set(cache_key, headerlist, cache_timeout) # 這里返回的才是頁面內(nèi)容對(duì)應(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 # 因此,請求同一個(gè)接口,但是接口參數(shù)不同,會(huì)生成兩個(gè)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字段,還是會(huì)針對(duì)當(dāng)前 cache_header_key 存一個(gè)空數(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)請求頭不同的時(shí)候,有可能會(huì)使用同一個(gè)緩存,這取決于不同的請求頭字段名是否出現(xiàn)在響應(yīng)頭Vary字段中。比如,如果響應(yīng)頭中有 Vary: User-Agent ,那么 User-Agent 不同的兩個(gè)請求必然生成不同的 cache_key,因此就不會(huì)使用同一個(gè)緩存。但如果只是在請求頭加一個(gè) cache-control: no-cache (瀏覽器提供的Disable cache功能),訪問同樣的url,那還是會(huì)命中之前的緩存的
到此這篇關(guān)于淺談Django 頁面緩存的cache_key是如何生成的的文章就介紹到這了,更多相關(guān)Django cache_key頁面緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Django緩存Cache使用詳解
- Django實(shí)現(xiàn)內(nèi)容緩存實(shí)例方法
- Django如何使用redis作為緩存
- django框架用戶權(quán)限中的session緩存到redis中的方法
- Django中提供的6種緩存方式詳解
- Django緩存系統(tǒng)實(shí)現(xiàn)過程解析
- Django 緩存配置Redis使用詳解
- 全面了解django的緩存機(jī)制及使用方法
- 簡單了解django緩存方式及配置
- Django使用redis緩存服務(wù)器的實(shí)現(xiàn)代碼示例
- Django項(xiàng)目如何配置Memcached和Redis緩存?選擇哪個(gè)更有優(yōu)勢?
相關(guān)文章
Python使用正則表達(dá)式獲取網(wǎng)頁中所需要的信息
這篇文章主要介紹了Python使用正則獲取網(wǎng)頁中所需要的信息的相關(guān)資料,需要的朋友可以參考下2018-01-01用python實(shí)現(xiàn)各種數(shù)據(jù)結(jié)構(gòu)
這篇文章主要分享的是用python實(shí)現(xiàn)各種數(shù)據(jù)結(jié)構(gòu),快速排序、選擇排序、插入排序、歸并排序、堆排序heapq模塊等相關(guān)資料,感興趣的小伙伴可以參考一下2021-12-12Python通過30秒就能學(xué)會(huì)的漂亮短程序代碼(過程全解)
這篇文章主要介紹了Python之30秒就能學(xué)會(huì)的漂亮短程序代碼,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-10-10Python unittest discover批量執(zhí)行代碼實(shí)例
這篇文章主要介紹了Python unittest discover批量執(zhí)行代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09Pandas中df.loc[]與df.iloc[]的用法與異同?
本文主要介紹了Pandas中df.loc[]與df.iloc[]的用法與異同,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧?2022-07-07Python+OpenCV實(shí)戰(zhàn)之拖拽虛擬方塊的實(shí)現(xiàn)
這篇文章主要介紹了如何利用Python+OpenCV實(shí)現(xiàn)拖拽虛擬方塊的效果,即根據(jù)手指坐標(biāo)位置和矩形的坐標(biāo)位置,判斷手指點(diǎn)是否在矩形上,如果在則矩形跟隨手指移動(dòng),感興趣的可以了解一下2022-08-08Python實(shí)現(xiàn)圖形用戶界面計(jì)算器
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)圖形用戶界面計(jì)算器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-07-07pandas進(jìn)行時(shí)間數(shù)據(jù)的轉(zhuǎn)換和計(jì)算時(shí)間差并提取年月日
這篇文章主要介紹了pandas進(jìn)行時(shí)間數(shù)據(jù)的轉(zhuǎn)換和計(jì)算時(shí)間差并提取年月日,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07