Python cachetools的持久化缓存。
项目描述
Shelved Cache
Python cachetools 的持久化缓存实现。
像任何 Cache
实现一样使用,但条目会被持久化到磁盘。
原始仓库: https://github.com/mariushelf/shelved_cache
使用示例
from shelved_cache import PersistentCache
from cachetools import LRUCache
filename = 'mycache'
# create persistency around an LRUCache
pc = PersistentCache(LRUCache, filename=filename, maxsize=2)
# we can now use the cache like a normal LRUCache.
# But: the cache is persisted to disk.
pc["a"] = 42
pc["b"] = 43
assert pc["a"] == 42
assert pc["b"] == 43
# close the file
pc.close()
# Now in the same script or in another script, we can re-load the cache:
pc2 = PersistentCache(LRUCache, filename=filename, maxsize=2)
assert pc2["a"] == 42
assert pc2["b"] == 43
用作装饰器
与常规的 cachetools.Cache
一样,PersistentCache
可以与 cachetools
' 的 cached
装饰器一起使用
import cachetools
from shelved_cache import PersistentCache
from cachetools import LRUCache
filename = 'mycache'
pc = PersistentCache(LRUCache, filename, maxsize=2)
@cachetools.cached(pc)
def square(x):
print("called")
return x * x
assert square(3) == 9
# outputs "called"
assert square(3) == 9
# no output because the cache is used
功能
持久化缓存
请参阅上面的使用示例。
异步装饰器
该软件包包含 cachetools
' 的 cached
和 cachedmethod
装饰器的等效功能,支持包装异步方法。您可以在 decorators
子模块中找到它们。
它们支持同步和异步函数和方法。
示例
from shelved_cache import cachedasyncmethod
from cachetools import LRUCache
class A:
# decorate an async method:
@cachedasyncmethod(lambda self: LRUCache(2))
async def asum(self, a, b):
return a + b
a = A()
assert await a.asum(1, 2) == 3
class S:
@cachedasyncmethod(lambda self: LRUCache(2))
def sum(self, a, b):
return a + b
s = S()
assert s.sum(1, 2) == 3
支持列表作为函数参数
使用 autotuple_hashkey
函数,列表参数会被自动转换为元组,以便支持哈希。
示例
from cachetools import cached, LRUCache
from shelved_cache.keys import autotuple_hashkey
@cached(LRUCache(2), key=autotuple_hashkey)
def sum(values):
return values[0] + values[1]
# fill cache
assert sum([1, 2]) == 3
# access cache
assert sum([1, 2]) == 3
变更日志
0.3.0
- 添加对Python 3.10和3.11的支持
- 当尝试使用同一文件为多个缓存时,错误消息更友好
- CI/CD管道
- 文档修复
0.2.1
- 改进错误处理
致谢
- cachetools by Thomas Kemmer
- asyncache by hephex
许可证
作者:Marius Helf (helfsmarius@gmail.com)
许可证:MIT -- 查看 LICENSE