RetryHTTP
RetryHTTP is a Python library designed to simplify retrying potentially transient HTTP errors. It extends the `tenacity` library with custom retry and wait strategies, offering sensible defaults while remaining fully customizable. The library provides decorators to automatically retry HTTP requests in applications using `requests`, `httpx`, or `aiohttp`.
Warnings
- gotcha Be cautious when retrying non-idempotent HTTP methods like POST, PUT, or DELETE by default. While `retryhttp` has sensible defaults for many scenarios, blindly retrying these can lead to unintended side effects (e.g., duplicate resource creation). Always understand your API's idempotency guarantees.
- gotcha For full integration and client-specific error handling, remember to install `retryhttp` with the relevant optional dependencies (e.g., `pip install retryhttp[httpx]` for HTTPX support). Without these, `retryhttp` may still catch generic exceptions but won't be able to leverage client-specific error types for more granular retry logic.
- gotcha If customizing retry behavior, be aware that `retryhttp` extends `tenacity`. While it provides its own decorator, deeper customizations might involve understanding `tenacity`'s retry strategies, wait strategies, and stop conditions. Ensure your custom logic correctly integrates with `retryhttp`'s opinionated defaults.
Install
-
pip install retryhttp -
pip install retryhttp[httpx] -
pip install retryhttp[requests] -
pip install retryhttp[aiohttp]
Imports
- retry
from retryhttp import retry
Quickstart
import httpx
from retryhttp import retry
@retry
def fetch_data_with_retries():
"""Fetches data from example.com, retrying on transient HTTP errors."""
print("Attempting to fetch data...")
try:
response = httpx.get("https://example.com/")
response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
print("Successfully fetched data!")
return response.text
except httpx.HTTPStatusError as e:
print(f"HTTP error occurred: {e.response.status_code}")
raise # Re-raise to trigger retry logic if it's a retryable status
except httpx.RequestError as e:
print(f"Request error occurred: {e}")
raise # Re-raise to trigger retry logic on network errors/timeouts
if __name__ == "__main__":
data = fetch_data_with_retries()
# In a real scenario, you'd process 'data' here
# For this example, we just show successful fetch or final failure