【问题标题】:Python check if cache key existsPython检查缓存键是否存在
【发布时间】:2020-02-23 07:06:34
【问题描述】:

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

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

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

【问题讨论】:

    标签: python python-3.x caching


    【解决方案1】:

    在不使用装饰器的情况下像普通字典一样访问缓存

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

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 2013-08-07
      • 1970-01-01
      • 2023-03-30
      • 2015-12-04
      • 2012-09-08
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      相关资源
      最近更新 更多