跳转到主要内容

Python cachetools的持久化缓存。

项目描述

Shelved Cache

Tests codecov PyPI version

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' 的 cachedcachedmethod 装饰器的等效功能,支持包装异步方法。您可以在 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

  • 改进错误处理

致谢

许可证

作者:Marius Helf (helfsmarius@gmail.com)

许可证:MIT -- 查看 LICENSE

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源代码发行版

shelved_cache-0.3.1.tar.gz (7.2 kB 查看哈希值)

上传时间 源代码

构建发行版

shelved_cache-0.3.1-py3-none-any.whl (7.8 kB 查看哈希值)

上传时间 Python 3

支持

AWSAWS 云计算和安全赞助商 DatadogDatadog 监控 FastlyFastly CDN GoogleGoogle 下载分析 MicrosoftMicrosoft PSF赞助商 PingdomPingdom 监控 SentrySentry 错误日志 StatusPageStatusPage 状态页面