跳转到主要内容

适用于asyncio的简单LRU缓存

项目描述

info:

Simple lru cache for asyncio

GitHub Actions CI/CD workflows status async-lru @ PyPI https://codecov.io/gh/aio-libs/async-lru/branch/master/graph/badge.svg Matrix Room — #aio-libs:matrix.org Matrix Space — #aio-libs-space:matrix.org

安装

pip install async-lru

用法

本软件包是Python内置的functools.lru_cache函数的asyncio版本。为了更好地处理异步行为,它还确保多个并发调用只会调用包装函数一次,所有await都会在调用完成后接收到该调用的结果。

import asyncio

import aiohttp
from async_lru import alru_cache


@alru_cache(maxsize=32)
async def get_pep(num):
    resource = 'https://pythonlang.cn/dev/peps/pep-%04d/' % num
    async with aiohttp.ClientSession() as session:
        try:
            async with session.get(resource) as s:
                return await s.read()
        except aiohttp.ClientError:
            return 'Not Found'


async def main():
    for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
        pep = await get_pep(n)
        print(n, len(pep))

    print(get_pep.cache_info())
    # CacheInfo(hits=3, misses=8, maxsize=32, currsize=8)

    # closing is optional, but highly recommended
    await get_pep.cache_close()


asyncio.run(main())

支持TTL(生存时间,超时失效),通过接受ttl配置参数(默认关闭)

@alru_cache(ttl=5)
async def func(arg):
    return arg * 2

该库支持通过cache_invalidate()显式使特定函数调用无效

@alru_cache(ttl=5)
async def func(arg1, arg2):
    return arg1 + arg2

func.cache_invalidate(1, arg2=2)

如果对应的参数集合已被缓存,则该方法返回True,否则返回False

需要Python 3.8+

谢谢

该库由Ocean S.A.捐赠

感谢公司的贡献。

项目详情


下载文件

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

源分布

async-lru-2.0.4.tar.gz (10.0 kB 查看散列)

上传时间

构建分布

async_lru-2.0.4-py3-none-any.whl (6.1 kB 查看散列)

上传时间 Python 3

支持者