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