我有以下使用缓存函数的 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
有没有办法先检查缓存中是否存在 key ,以便我可以实现其他功能?
当此处不存在缓存键时,我正在尝试实现另一个缓存以从那里获取数据。
最佳答案
不使用装饰器像普通字典一样访问缓存
item = cache.get(key, None)
if item is not None:
...
else:
...
# get item the slow way
cache[key] = item
关于Python检查缓存键是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58583762/