gpt4 book ai didi

Python检查缓存键是否存在

转载 作者:行者123 更新时间:2023-12-02 19:49:11 25 4
gpt4 key购买 nike

我有以下使用缓存函数的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com