簡體   English   中英

Python 檢查緩存鍵是否存在

[英]Python check if cache key exists

我有以下使用緩存功能的 python function :

from cachetools import cached, TTLCache

cache = TTLCache(maxsize=100, ttl=3600)

@cached(cache)
def load_data():
   # run slow data to get all user data
   load_response = requests.request(
       'GET',
       url=my_url
   )

   return load_response

有沒有辦法先檢查緩存中是否存在密鑰,以便我可以實現其他功能?

當此處不存在緩存鍵時,我正在嘗試實現另一個緩存以從那里獲取數據。

在不使用裝飾器的情況下像普通字典一樣訪問緩存

item = cache.get(key, None)
if item is not None:
   ...
else:
   ...
   # get item the slow way
   cache[key] = item

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM