Python内存缓存与时间到li

2024-05-08 12:36:36 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

您可以使用^{}模块:

The core of the library is ExpiringDict class which is an ordered dictionary with auto-expiring values for caching purposes.

在描述中,它们不讨论多线程,因此为了不弄糟,请使用Lock

OP使用的是Python2.7,但如果您使用的是Python3,则接受的答案中提到的ExpiringDict目前已经过期。对github repo的最后一次提交是2017年6月17日,有一个公开的问题是它doesn't work with Python 3.5

有一个最近维护的项目cachetools(上次提交时间:2018年6月14日)

pip install cachetools

from cachetools import TTLCache

cache = TTLCache(maxsize=10, ttl=360)
cache['apple'] = 'top dog'
...
>>> cache['apple']
'top dog'
... after 360 seconds...
>>> cache['apple']
KeyError exception thrown

ttl是以秒为单位的生存时间。

如果您不想使用任何第三个库,您可以在昂贵的函数中再添加一个参数:ttl_hash=None。这个新参数被称为“时间敏感哈希”,其唯一目的是影响lru_cache

例如:

from functools import lru_cache
import time


@lru_cache()
def my_expensive_function(a, b, ttl_hash=None):
    del ttl_hash  # to emphasize we don't use it and to shut pylint up
    return a + b  # horrible CPU load...


def get_ttl_hash(seconds=3600):
    """Return the same value withing `seconds` time period"""
    return round(time.time() / seconds)


# somewhere in your code...
res = my_expensive_function(2, 2, ttl_hash=get_ttl_hash())
# cache will be updated once in an hour

相关问题 更多 >