濮阳杆衣贸易有限公司

主頁(yè) > 知識(shí)庫(kù) > 淺談Django 頁(yè)面緩存的cache_key是如何生成的

淺談Django 頁(yè)面緩存的cache_key是如何生成的

熱門標(biāo)簽:汕頭電商外呼系統(tǒng)供應(yīng)商 賓館能在百度地圖標(biāo)注嗎 鄭州智能外呼系統(tǒng)中心 400電話 申請(qǐng) 條件 crm電銷機(jī)器人 云南地圖標(biāo)注 南京crm外呼系統(tǒng)排名 北京外呼電銷機(jī)器人招商 電銷機(jī)器人 金倫通信

頁(yè)面緩存

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ù)請(qǐng)求和響應(yīng)參數(shù)、設(shè)定的key_prefix生成頁(yè)面緩存的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 的請(qǐng)求獲取緩存
  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ù)請(qǐng)求的信息、緩存鍵前綴生成一個(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

頁(yè)面緩存的cache_key

這一節(jié)將回答兩個(gè)問題:

  1. 為什么在redis中,一個(gè)頁(yè)面會(huì)保存兩個(gè)key:cache_key以及cache_header?
  2. 頁(yè)面緩存是如何被唯一標(biāo)識(shí)的?當(dāng)請(qǐng)求頭不同的時(shí)候(比如換了一個(gè)用戶請(qǐng)求相同的頁(yè)面)會(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ù)請(qǐng)求頭 `User-Agent` 的值有所不同
 # 只有當(dāng)下一個(gè)請(qǐng)求的 `User-Agent` 值與當(dāng)前請(qǐ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)
  # 這里返回的才是頁(yè)面內(nèi)容對(duì)應(yīng)的 cache_key,它由 
  # 出現(xiàn)在Vary字段中的request請(qǐng)求頭字段的值(有序拼在一起)、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()返回的是完整的請(qǐng)求URL。如 http://127.0.0.1:8000/api/leaflet/filterList?a=1
 # 因此,請(qǐng)求同一個(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請(qǐng)求頭字段的值
  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)前請(qǐng)求具有相同cache_header_key 的請(qǐng)求的響應(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)前請(qǐng)求沒有緩存
 if headerlist is not None:
  # 根據(jù) 出現(xiàn)在Vary字段中的request請(qǐng)求頭字段的值(有序拼在一起)、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請(qǐng)求頭字段的值(有序拼在一起)、request的完整url、request的method、key_prefix 唯一確定
  • 當(dāng)請(qǐng)求頭不同的時(shí)候,有可能會(huì)使用同一個(gè)緩存,這取決于不同的請(qǐng)求頭字段名是否出現(xiàn)在響應(yīng)頭Vary字段中。比如,如果響應(yīng)頭中有 Vary: User-Agent ,那么 User-Agent 不同的兩個(gè)請(qǐng)求必然生成不同的 cache_key,因此就不會(huì)使用同一個(gè)緩存。但如果只是在請(qǐng)求頭加一個(gè) cache-control: no-cache (瀏覽器提供的Disable cache功能),訪問同樣的url,那還是會(huì)命中之前的緩存的

到此這篇關(guān)于淺談Django 頁(yè)面緩存的cache_key是如何生成的的文章就介紹到這了,更多相關(guān)Django cache_key頁(yè)面緩存內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(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ī)制及使用方法
  • 簡(jiǎn)單了解django緩存方式及配置
  • Django使用redis緩存服務(wù)器的實(shí)現(xiàn)代碼示例
  • Django項(xiàng)目如何配置Memcached和Redis緩存?選擇哪個(gè)更有優(yōu)勢(shì)?

標(biāo)簽:昆明 西寧 懷化 石家莊 文山 浙江 梅州 錫林郭勒盟

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《淺談Django 頁(yè)面緩存的cache_key是如何生成的》,本文關(guān)鍵詞  淺談,Django,頁(yè)面,緩存,的,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《淺談Django 頁(yè)面緩存的cache_key是如何生成的》相關(guān)的同類信息!
  • 本頁(yè)收集關(guān)于淺談Django 頁(yè)面緩存的cache_key是如何生成的的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    合水县| 抚远县| 宿州市| 大理市| 石屏县| 固安县| 建昌县| 秦皇岛市| 安吉县| 唐山市| 泾川县| 德州市| 黑山县| 徐州市| 和政县| 黎川县| 抚顺县| 柳江县| 怀安县| 浦江县| 崇仁县| 孟州市| 马关县| 皋兰县| 中卫市| 庄河市| 阳城县| 琼结县| 元阳县| 仁寿县| 连城县| 宁远县| 松阳县| 灯塔市| 永昌县| 抚顺市| 平果县| 永和县| 民权县| 德令哈市| 朝阳市|