aiohttp-retry
aiohttp-retry is a simple retry client for aiohttp, providing robust request retrying capabilities for asynchronous HTTP operations. It supports various retry strategies like exponential backoff and random delays. The current version is 2.9.1 and it requires Python 3.7 or higher. The library is actively maintained with regular releases addressing bug fixes and introducing new features.
Warnings
- breaking Version 2.0 introduced backward incompatible changes. If upgrading from versions prior to 2.0 (e.g., v1.2), expect breaking changes in API usage.
- breaking The `evaluate_response_callback` feature introduced a bug in versions 2.7.0 through 2.8.3 that could lead to infinite retries. These versions were yanked from PyPI.
- gotcha Since version 2.5.6, the `get_timeout` function in custom `RetryOptions` now receives an additional `response` parameter. If you have defined your own `RetryOptions` and custom `get_timeout` logic, it needs to be updated.
- gotcha When using `ExponentialRetry` or similar, setting `start_timeout` and `factor` to 0 will cause all retries to occur in quick succession without any delay, defeating the purpose of a backoff strategy.
- gotcha By default, `RetryClient` retries on all 5xx HTTP responses. If you want to specify custom 5xx errors or disable default 5xx retries, you must pass `retry_all_server_errors=False` in `RetryClient` constructor and explicitly define `statuses` in `RetryOptions`.
Install
-
pip install aiohttp-retry
Imports
- RetryClient
from aiohttp_retry import RetryClient
- ExponentialRetry
from aiohttp_retry import ExponentialRetry
- RandomRetry
from aiohttp_retry import RandomRetry
- RetryOptions
from aiohttp_retry import RetryOptions
- RequestParams
from aiohttp_retry import RequestParams
Quickstart
import asyncio
from aiohttp_retry import RetryClient, ExponentialRetry
async def main():
# Configure retry options, e.g., 3 attempts with exponential backoff
retry_options = ExponentialRetry(attempts=3, start_timeout=0.1, factor=2)
# Create a RetryClient instance
# raise_for_status=False prevents aiohttp from raising exceptions for HTTP error statuses,
# allowing aiohttp-retry to handle them based on its retry logic.
async with RetryClient(raise_for_status=False, retry_options=retry_options) as retry_client:
try:
# Make a GET request that will be retried on failure
async with retry_client.get('https://httpbin.org/status/500', retry_attempts=3) as response:
print(f"Final status: {response.status}")
print(f"Content-type: {response.headers.get('Content-Type')}")
except Exception as e:
print(f"Request failed after retries: {e}")
if __name__ == '__main__':
asyncio.run(main())