跳转到主要内容

aiohttp 请求的持久缓存

项目描述

aiohttp-client-cache

Build status Documentation Status Codecov PyPI Conda PyPI - Python Versions PyPI - Format

aiohttp-client-cache 是一个基于 requests-cacheaiohttp 客户端请求的异步持久缓存。

特性

  • 易用性: 作为 drop-in replacement 用于 aiohttp.ClientSession
  • 自定义: 默认情况下无需配置即可运行,但提供了大量选项来自定义缓存 过期 和其他 行为
  • 持久性: 包含多个 存储后端:SQLite、DynamoDB、MongoDB、DragonflyDB 和 Redis。

快速入门

首先,使用 pip 安装(需要 python 3.8+)

pip install aiohttp-client-cache[all]

注意:添加 [all] 将为所有支持的后端安装可选依赖项。当将此库添加到您的应用程序中时,您只需包含您实际需要的依赖项;有关详细信息,请参阅各个后端文档和 pyproject.toml

基本用法

接下来,使用 aiohttp_client_cache.CachedSession 替代 aiohttp.ClientSession。为了简要说明如何使用它

替换这个

from aiohttp import ClientSession

async with ClientSession() as session:
    await session.get('http://httpbin.org/delay/1')

用这个

from aiohttp_client_cache import CachedSession, SQLiteBackend

async with CachedSession(cache=SQLiteBackend('demo_cache')) as session:
    await session.get('http://httpbin.org/delay/1')

此示例中的 URL 添加了 1 秒的延迟,模拟缓慢或速率限制的网站。使用缓存后,响应将只获取一次,保存到 demo_cache.sqlite,后续请求将几乎立即返回缓存的响应。

配置

有几个选项可用于自定义缓存行为。此示例演示了其中的一些

# fmt: off
from aiohttp_client_cache import SQLiteBackend

cache = SQLiteBackend(
    cache_name='~/.cache/aiohttp-requests.db',  # For SQLite, this will be used as the filename
    expire_after=60*60,                         # By default, cached responses expire in an hour
    urls_expire_after={'*.fillmurray.com': -1}, # Requests for any subdomain on this site will never expire
    allowed_codes=(200, 418),                   # Cache responses with these status codes
    allowed_methods=['GET', 'POST'],            # Cache requests with these HTTP methods
    include_headers=True,                       # Cache requests with different headers separately
    ignored_params=['auth_token'],              # Keep using the cached response even if this param changes
    timeout=2.5,                                # Connection timeout for SQLite backend
)

更多信息

要了解更多信息,请参阅

反馈

如果您想添加功能,如果您发现了错误,或如果您有其他一般性反馈,请为它 创建一个问题

项目详情


下载文件

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

源分发

aiohttp_client_cache-0.12.3.tar.gz (62.6 kB 查看哈希值)

上传时间

构建分发

aiohttp_client_cache-0.12.3-py3-none-any.whl (32.5 kB 查看哈希值)

上传时间 Python 3

支持者