随笔 - 836  文章 - 1 评论 - 40 阅读 - 102万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

python dict和ttl支持自动过期缓存

 

github: https://github.com/mailgun/expiringdict

  安装

pip install expiringdict
pip install expiring-dict
使用:
复制代码
from expiringdict import ExpiringDict
from datetime import timedelta

# 创建一个带有过期时间的字典,过期时间为5秒
cache = ExpiringDict(max_len=100, max_age_seconds=5)

# 向字典中添加键值对
cache['key1'] = 'value1'
cache['key2'] = 'value2'

# 从字典中获取键值对
print(cache['key1'])  # 输出: value1

# 等待5秒钟
import time
time.sleep(5)

# 尝试获取已过期的键值对
print(cache.get('key1'))  # 输出: None

# 尝试获取未过期的键值对
print(cache.get('key2'))  # 输出: value2
复制代码

 

 

复制代码
Create a dictionary with capacity for 100 elements and elements expiring in 10 seconds:

from expiringdict import ExpiringDict
cache = ExpiringDict(max_len=100, max_age_seconds=10)
put and get a value there:

cache["key"] = "value"
cache.get("key")


copy
from dict or OrderedDict: from expiringdict import ExpiringDict my_dict=dict() my_dict['test'] = 1 cache = ExpiringDict(max_len=100, max_age_seconds=10, items=my_dict) assert cache['test'] == 1


copy from another ExpiringDict, with or without new length and timeout: from expiringdict import ExpiringDict cache_hour = ExpiringDict(max_len=100, max_age_seconds=3600) cache_hour['test'] = 1 cache_hour_copy = ExpiringDict(max_len=None, max_age_seconds=None, items=cache_hour) cache_minute_copy = ExpiringDict(max_len=None, max_age_seconds=60, items=cache_hour) assert cache_minute_copy['test'] == 1


pickle : import dill from expiringdict import ExpiringDict cache = ExpiringDict(max_len=100, max_age_seconds=10) cache['test'] = 1 pickled_cache = dill.dumps(cache) unpickled_cache = dill.loads(cache) assert unpickled_cache['test'] == 1
复制代码

 



 
posted on   lshan  阅读(477)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2019-10-08 python 单元测试
点击右上角即可分享
微信分享提示