python utils和decorators,用于使用ttl、maxsize和基于文件的存储的c_ching。
caching-py35的Python项目详细描述
状态
正在工作
安装
pip install caching
用法
fromcachingimportCache# File-based cache with unlimited ttl and maximum of 128 cached results@Cache(ttl=-1,maxsize=128,filepath='/tmp/mycache')deflong_running_function(a,b,*args,c=None,**kwargs):pass# Memory-based cache with limited ttl and maxsize and "least recently used"# cache replacement policy.@Cache(ttl=60,maxsize=128,policy='LRU')deflong_running_function(a,b,*args,c=None,**kwargs):pass
高级用法
fromcachingimportCache# One cache for many functionscache=Cache(filepath='/tmp/mycache',ttl=3600,maxsize=1024)@cachedefpow(x,y):returnx**y@cachedeffactorial(n):ifn==0:return1returnn*factorial(n-1)# Caching the last result and returning it only in case of errors@Cache(maxsize=1,only_on_errors=(ConnectionError,TimeoutError))defapi_request():"""Request some remote resource which sometimes become unavailable. If this functions raises ConnectionError or TimeoutError, then the last cached result will be returned, if available."""# Custom cache key function@Cache(key=lambdax:x[0])deftoupper(a):globalcall_countcall_count+=1returnstr(a).upper()call_count=0# The key function returns the same result for both 'aaa' and 'azz'# so the cached result from the first call is returned in the second callasserttoupper('aaa')==toupper('azz')=='AAA'assertcall_count==1# Using cache as a key-value storecache=Cache()try:result=cache[1]exceptKeyError:result=calculate_result(1)cache[1]=resultassert1incacheassertcache[1]==resultassertcache.get(1,None)==resultassertcache.get(2,None)isNone# Cleanupimportoscache=Cache(filepath='/tmp/mycache')cache[1]='one'assert1incachecache.clear()# empty the cacheassert1notincacheassertlist(cache.items())==[]assertos.path.isfile('/tmp/mycache')cache.remove()# Empty the cache and remove the underlying fileassertnotos.path.isfile('/tmp/mycache')
功能
- [x]基于内存和文件的缓存
- [x]TTL和maxsize
- [x]与*args,**kwargs一起工作
- [X]使用以下类型的可变函数参数:^{TT4}$,^{TT5}$,^{TT6}$。
- [X]FIFO、LRU和LFU缓存替换策略。
- [X]可定制的缓存键功能。
- []多处理-线程安全
- []可插入的外部缓存后端(请参阅redis示例)。