本项目提供了一个异步请求重试机制,旨在处理网络请求中的失败情况。通过使用装饰器,可以轻松地为异步函数添加重试逻辑,以确保在请求失败时能够自动重试,直到达到最大重试次数或成功为止。
Project description
使用说明 - 异步请求重试机制
简介
本项目提供了一个异步请求重试机制,旨在处理网络请求中的失败情况。通过使用装饰器,可以轻松地为异步函数添加重试逻辑,以确保在请求失败时能够自动重试,直到达到最大重试次数或成功为止。
主要组件
- StateManager: 单例模式的状态管理器,用于管理请求的状态。
- RequestResult: 封装请求结果及其尝试次数的类。
- Retrier: 管理重试逻辑的类,负责执行请求并根据条件决定是否重试。
- retry_on_condition: 装饰器,用于包装需要重试的异步函数。
安装依赖
在使用本项目之前,请确保安装了以下依赖库:
pip install httpx loguru
使用示例
1. 定义异步请求函数
首先,定义一个异步函数,该函数将执行实际的网络请求。例如:
import httpx
async def fetch_data(url: str) -> httpx.Response:
async with httpx.AsyncClient() as client:
response = await client.get(url)
response.raise_for_status() # 如果响应状态码不是200,将引发异常
return response
2. 使用装饰器添加重试逻辑
使用 retry_on_condition 装饰器来包装你的异步请求函数,以添加重试逻辑。例如:
@retry_on_condition(max_attempts=5, retry_delay=2.0)
async def fetch_with_retry(url: str) -> RequestResult[httpx.Response]:
return await fetch_data(url)
3. 调用函数并处理结果
调用带有重试逻辑的函数,并处理返回的结果:
import asyncio
async def main():
url = "https://api.example.com/data"
result = await fetch_with_retry(url)
if result.result is not None:
print("请求成功:", result.result)
else:
print(f"请求失败,尝试次数: {result.attempts}")
if __name__ == "__main__":
asyncio.run(main())
参数说明
retry_on_condition 装饰器参数
max_attempts: 最大重试次数,默认为30次。
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
httpretry-0.1.0.tar.gz
(4.0 kB
view details)
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file httpretry-0.1.0.tar.gz.
File metadata
- Download URL: httpretry-0.1.0.tar.gz
- Upload date:
- Size: 4.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.1 CPython/3.10.8 Windows/10
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ca1d057edf0cc69732ec085d09110226f78ee4eb3a4d3737d5a2027b6164907b
|
|
| MD5 |
11c91cc660ac1c9d5accaceba1e0b510
|
|
| BLAKE2b-256 |
f2f4c0464bc0abcf4165521a5545aa539edfb4a5e5918e936b575d9c270d4255
|
File details
Details for the file httpretry-0.1.0-py3-none-any.whl.
File metadata
- Download URL: httpretry-0.1.0-py3-none-any.whl
- Upload date:
- Size: 4.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.1 CPython/3.10.8 Windows/10
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
60f2308feeea01f253cce67eabc558f75a0811a686c7678dece866055f17088d
|
|
| MD5 |
0948378fdd531883ceb90e2a644c230d
|
|
| BLAKE2b-256 |
f85d7c41ff84161ac5bfaf6853e51c22e568addd47c577aa0e03f8784cf987d9
|