Python 检查缓存键是否存在

Abh*_*hek 2 python caching python-3.x

我有以下使用缓存函数的 python 函数:

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
Run Code Online (Sandbox Code Playgroud)

有没有办法首先检查密钥是否存在于缓存中,以便我可以实现其他功能?

当此处不存在缓存键时,我正在尝试实现另一个缓存以从那里获取数据。

Lio*_*hen 7

像普通字典一样访问缓存,无需使用装饰器

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