python - 为什么 python3 lru_cache 不提供 put 和 query 方法?

标签 python python-3.x caching lru

这是我的情况,is_exist 函数有性能问题。

def is_exist(link :str) -> bool:
    if query_db(link) is True:
         return True
    return False

def process(link: str)
   if is_exist(link) is True:
       return
   # do something
   # put result to database

LRU 缓存是一个很好的解决方案,但是经过几个小时的努力我发现 lru_cache 不满足我的要求。我想要这样的:

def is_exist(link :str) -> bool:
    if query_db(link) is True:
         return True
    return False

def process(link: str)
   if lru_cache.query(link) is True:
      return

   if is_exist(link) is True:
       lru_cache.add(link)
       return
   # do something
   # put result to database

functiontools 中的 LRU Cache 是一个装饰器。它没有查询方法。如果我使用 @lru_cache 装饰 is_exist,则当 is_exist 返回 false 时,某些链接将被重复处理。

PS:将结果放入数据库是异步的

最佳答案

functools.lru_cache 仅缓存结果,但不缓存异常。这意味着函数应该在任何情况下引发异常,并且稍后必须重新评估该异常。

@lru_cache
def is_exist(link: str) -> bool:
    if query_db(link):
         return True   # added to cache
    raise LookupError  # ignored by cache

这允许客户端功能使用缓存进行检查,但仍然插入丢失的条目。

def process(link: str)
   try:
       is_exist(link)
   except LookupError:
       # do something
       # put result to database

关于python - 为什么 python3 lru_cache 不提供 put 和 query 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68663883/

相关文章:

python - 安装软件包后 Conda 冲突未解决

python - mypy:定义动态字典中特定键的类型

python-3.x - 使用 aiohttp.post 我如何将一些数据传递给它以进行迭代

python - Python 中文件串联的 ValueError

python - Amazon S3cmd 在某些大型上传时崩溃

python - 计算 n 个进程下载到可用存储的磁盘已满时间

linux - L1 数据缓存配置

asp.net - 负载平衡的 ASP.NET Web 应用程序中的跨服务器通信

python - Cherrypy 和 JSON Arduino Web 界面

Codeigniter缓存 Controller 问题