Python检查缓存键是否存在

标签 python python-3.x caching

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

相关文章:

python - Celery:运行具有 super 用户权限的 worker

svn - 我在哪里可以免费获得 Subversion 中的日志缓存?

php - 在 MAMP 服务器上安装 APCu

java - 如果达到内存大小限制,如何从 map 中删除元素?

python - 将逗号分隔的 .txt 文件转换为字典

python - 正则表达式:匹配所有内容,直到 `:` 或 `(`

Python,如何用一级路径替换 "anything"或 "*"

python - 确定 Python 中特定数字的精度和小数位数

python - 获取数组的最后一个索引的时间复杂度是多少?

python - 使用 Python v3.x 和 C API 解释 Python v2.5 代码(关于整数除法)