aiohttp 请求的持久缓存
项目描述
aiohttp-client-cache
aiohttp-client-cache 是一个基于 requests-cache 的 aiohttp 客户端请求的异步持久缓存。
特性
- 易用性: 作为 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.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 184661458e46773a6b5d5da9e9cd916a11e540c523bff2928dea6d52142b1026 |
|
MD5 | ef7feecc0e551a24d8ef698525f717e6 |
|
BLAKE2b-256 | 1e8960d829fa323e01006e8c6e76133284ae2ffd692752706e18db162f32df75 |
关闭
aiohttp_client_cache-0.12.3-py3-none-any.whl 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 7bc03d5352714969a180ab7be70c1d02141c22bc759f79f7c8207b7c473c8184 |
|
MD5 | ff85f35e6a430e5bdd4a6b5a33dd2f36 |
|
BLAKE2b-256 | f4da428cd74591e7ba46e36a14e8cc9566c14486f3c5b8a92eff1de728460908 |