Reference API
Retry policies¶
The following symbols are exposed to the user by the client-independent package root:
httpx_tenacity
¶
Provide the retry policies that configure the tenacious transports.
This package imports no HTTP client. The transports live in the integration
packages, httpx_tenacity.httpx for HTTPX and httpx_tenacity.httpx2 for
HTTPX2. Each of them requires its own extra.
RetryingT = TypeVar('RetryingT', tenacity.Retrying, tenacity.AsyncRetrying)
module-attribute
¶
The sync or async tenacity retrying class that a retry policy creates.
RetryPolicy
¶
Bases: Protocol
Define the interface of a retry policy.
A tenacious transport's create() factory calls the policy's create() method
with the tenacity retrying class it needs, its HTTP client's base exception for
failed requests, and its logger.
create(retrying_class: type[RetryingT], *, request_error: type[Exception], logger: logging.Logger) -> RetryingT
¶
Create a retrying instance for a transport.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
retrying_class
|
type[RetryingT]
|
Either |
required |
request_error
|
type[Exception]
|
The HTTP client's base exception for failed requests, such
as |
required |
logger
|
Logger
|
The transport's logger. |
required |
Returns:
| Type | Description |
|---|---|
RetryingT
|
An instance of the given retrying class. |
SmartRetryPolicy
¶
Bases: NamedTuple
Define the default retry policy.
The policy retries request errors and server-side issues. Between attempts, it waits for the time given in a response header when the response has one of the expected status codes, and otherwise uses random exponential backoff.
Attributes:
| Name | Type | Description |
|---|---|---|
max_attempts |
int
|
Maximum number of attempts. |
multiplier |
float
|
Multiplier for the exponential backoff between retries. |
max_wait_seconds |
float | timedelta
|
Maximum wait time between retries. |
min_wait_seconds |
float | timedelta
|
Minimum wait time between retries. |
exponent_base |
float
|
The base for the exponential backoff. |
status_code |
int | tuple[int, ...]
|
The response status code or codes whose header sets the wait. |
header |
str
|
The response header that holds the wait time in seconds. |
exponent_base: float = 2
class-attribute
instance-attribute
¶
header: str = 'Retry-After'
class-attribute
instance-attribute
¶
max_attempts: int = 5
class-attribute
instance-attribute
¶
max_wait_seconds: float | timedelta = 60
class-attribute
instance-attribute
¶
min_wait_seconds: float | timedelta = 0.02
class-attribute
instance-attribute
¶
multiplier: float = 1
class-attribute
instance-attribute
¶
status_code: int | tuple[int, ...] = HTTPStatus.TOO_MANY_REQUESTS
class-attribute
instance-attribute
¶
create(retrying_class: type[RetryingT], *, request_error: type[Exception], logger: logging.Logger) -> RetryingT
¶
Create a retrying instance with this policy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
retrying_class
|
type[RetryingT]
|
Either |
required |
request_error
|
type[Exception]
|
The HTTP client's base exception for failed requests, such
as |
required |
logger
|
Logger
|
The logger that records each retry at DEBUG level. |
required |
Returns:
| Type | Description |
|---|---|
RetryingT
|
An instance of the given retrying class. |
The following helpers, which the default policy is built from, are client-independent as well. They are not exported by the package root, so import them from their own modules:
smart_waitfromhttpx_tenacity.waitis_server_side_issuefromhttpx_tenacity.retry_callback
httpx_tenacity.wait
¶
Provide custom wait functions.
smart_wait
¶
Bases: wait_random_exponential
Define a wait strategy that smartly backs-off.
This strategy first checks HTTP responses for an expected status code (by default 429) that indicates that the server is busy. If the status code matches, it checks the response header (by default 'Retry-After') for a wait time indication. Otherwise, it uses random exponential backoff.
__call__(retry_state: tenacity.RetryCallState) -> float
¶
Return a wait time in seconds based on response headers or retry state.
When we have a successful outcome, i.e., we received an HTTP response without encountering an exception, and the HTTP status code of the response matches the specified status code, check if the response header indicates a wait time; otherwise use the random exponential strategy to determine the wait time.
__init__(multiplier: float = 1, max: timedelta | float = 60, exp_base: float = 2, min: timedelta | float = 0, status_code: int | tuple[int, ...] = HTTPStatus.TOO_MANY_REQUESTS, header: str = 'Retry-After') -> None
¶
httpx_tenacity.retry_callback
¶
Provide custom retry callback functions.
is_server_side_issue(response: Response) -> bool
¶
Return whether the response indicates a server side issue.
A server side issue is defined as either an HTTP server error code (500 - 599) or too many requests (429).
HTTPX¶
The following symbols are exposed to the user by httpx_tenacity.httpx, which
requires the httpx extra:
httpx_tenacity.httpx
¶
Provide the HTTPX integration.
Importing this package requires the httpx extra, for example
pip install "httpx-tenacity[httpx]".
TenaciousTransport
¶
Bases: BaseTransport
Define the synchronous tenacious (retrying) transport.
This transport consists of a composed transport for handling requests and an appropriately configured tenacity retrying instance.
The transport owns the composed transport, including one that you pass in
yourself. Entering, exiting, or closing this transport does the same to the
composed transport, in the same way that httpx.Client treats its transport.
__enter__() -> Self
¶
Enter the composed transport and return this transport.
__exit__(exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: TracebackType | None = None) -> None
¶
Exit the composed transport, passing on any exception details.
__init__(*, retry: tenacity.Retrying, transport: httpx.BaseTransport, **kwargs: dict[str, object]) -> None
¶
close() -> None
¶
Close the composed transport.
create(policy: RetryPolicy | None = None, transport: httpx.BaseTransport | None = None, **kwargs: Unpack[HTTPXHTTPTransportKeywordArguments]) -> TenaciousTransport
classmethod
¶
Create an instance of a synchronous tenacious (retrying) transport.
This factory method constructs the instance with an underlying
httpx.HTTPTransport.
That transport is passed any additional keyword arguments.
The retry policy creates the tenacity retrying instance. The default
SmartRetryPolicy retries requests when there are server-side issues
and will either wait the time set in a Retry-After response header or use a
random exponential backoff.
The returned transport owns the underlying transport, including one passed in
as transport, and closes it when it is closed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
RetryPolicy | None
|
The retry policy. Defaults to |
None
|
transport
|
BaseTransport | None
|
Pass a transport instance to handle requests instead of the default one. |
None
|
**kwargs
|
Unpack[HTTPXHTTPTransportKeywordArguments]
|
Additional keyword arguments are used in the construction of an
|
{}
|
Returns:
| Type | Description |
|---|---|
TenaciousTransport
|
A default instance of the class created from the given arguments. |
handle_request(request: httpx.Request) -> httpx.Response
¶
Handle a synchronous request with retrying.
AsyncTenaciousTransport
¶
Bases: AsyncBaseTransport
Define the asynchronous tenacious (retrying) transport.
This transport consists of a composed transport for handling requests and an appropriately configured tenacity retrying instance.
The transport owns the composed transport, including one that you pass in
yourself. Entering, exiting, or closing this transport does the same to the
composed transport, in the same way that httpx.AsyncClient treats its transport.
__aenter__() -> Self
async
¶
Enter the composed transport and return this transport.
__aexit__(exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: TracebackType | None = None) -> None
async
¶
Exit the composed transport, passing on any exception details.
__init__(*, retry: tenacity.AsyncRetrying, transport: httpx.AsyncBaseTransport, **kwargs: dict[str, object]) -> None
¶
aclose() -> None
async
¶
Close the composed transport.
create(policy: RetryPolicy | None = None, transport: httpx.AsyncBaseTransport | None = None, **kwargs: Unpack[HTTPXHTTPTransportKeywordArguments]) -> AsyncTenaciousTransport
classmethod
¶
Create an instance of an asynchronous tenacious (retrying) transport.
This factory method constructs the instance with an underlying
httpx.AsyncHTTPTransport.
That transport is passed any additional keyword arguments.
The retry policy creates the tenacity retrying instance. The default
SmartRetryPolicy retries requests when there are server-side issues
and will either wait the time set in a Retry-After response header or use a
random exponential backoff.
The returned transport owns the underlying transport, including one passed in
as transport, and closes it when it is closed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
RetryPolicy | None
|
The retry policy. Defaults to |
None
|
transport
|
AsyncBaseTransport | None
|
Pass an asynchronous transport instance to handle requests instead of the default one. |
None
|
**kwargs
|
Unpack[HTTPXHTTPTransportKeywordArguments]
|
Additional keyword arguments are used in the construction of an
|
{}
|
Returns:
| Type | Description |
|---|---|
AsyncTenaciousTransport
|
A default instance of the class created from the given arguments. |
handle_async_request(request: httpx.Request) -> httpx.Response
async
¶
Handle an asynchronous request with retrying.
HTTPXHTTPTransportKeywordArguments
¶
Bases: TypedDict
Keyword arguments for the sync and async httpx HTTPTransport constructor.
cert: CertTypes | None
instance-attribute
¶
http1: bool
instance-attribute
¶
http2: bool
instance-attribute
¶
limits: httpx.Limits
instance-attribute
¶
local_address: str | None
instance-attribute
¶
proxy: ProxyTypes | None
instance-attribute
¶
retries: int
instance-attribute
¶
socket_options: Iterable[SocketOption] | None
instance-attribute
¶
trust_env: bool
instance-attribute
¶
uds: str | None
instance-attribute
¶
verify: ssl.SSLContext | str | bool
instance-attribute
¶
HTTPX2¶
The following symbols are exposed to the user by httpx_tenacity.httpx2, which
requires the httpx2 extra:
httpx_tenacity.httpx2
¶
Provide the HTTPX2 integration.
Importing this package requires the httpx2 extra, for example
pip install "httpx-tenacity[httpx2]".
TenaciousTransport
¶
Bases: BaseTransport
Define the synchronous tenacious (retrying) transport.
This transport consists of a composed transport for handling requests and an appropriately configured tenacity retrying instance.
The transport owns the composed transport, including one that you pass in
yourself. Entering, exiting, or closing this transport does the same to the
composed transport, in the same way that httpx2.Client treats its transport.
__enter__() -> Self
¶
Enter the composed transport and return this transport.
__exit__(exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: TracebackType | None = None) -> None
¶
Exit the composed transport, passing on any exception details.
__init__(*, retry: tenacity.Retrying, transport: httpx2.BaseTransport, **kwargs: dict[str, object]) -> None
¶
close() -> None
¶
Close the composed transport.
create(policy: RetryPolicy | None = None, transport: httpx2.BaseTransport | None = None, **kwargs: Unpack[HTTPX2HTTPTransportKeywordArguments]) -> TenaciousTransport
classmethod
¶
Create an instance of a synchronous tenacious (retrying) transport.
This factory method constructs the instance with an underlying
httpx2.HTTPTransport.
That transport is passed any additional keyword arguments.
The retry policy creates the tenacity retrying instance. The default
SmartRetryPolicy retries requests when there are server-side issues
and will either wait the time set in a Retry-After response header or use a
random exponential backoff.
The returned transport owns the underlying transport, including one passed in
as transport, and closes it when it is closed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
RetryPolicy | None
|
The retry policy. Defaults to |
None
|
transport
|
BaseTransport | None
|
Pass a transport instance to handle requests instead of the default one. |
None
|
**kwargs
|
Unpack[HTTPX2HTTPTransportKeywordArguments]
|
Additional keyword arguments are used in the construction of an
|
{}
|
Returns:
| Type | Description |
|---|---|
TenaciousTransport
|
A default instance of the class created from the given arguments. |
handle_request(request: httpx2.Request) -> httpx2.Response
¶
Handle a synchronous request with retrying.
AsyncTenaciousTransport
¶
Bases: AsyncBaseTransport
Define the asynchronous tenacious (retrying) transport.
This transport consists of a composed transport for handling requests and an appropriately configured tenacity retrying instance.
The transport owns the composed transport, including one that you pass in
yourself. Entering, exiting, or closing this transport does the same to the
composed transport, in the same way that httpx2.AsyncClient treats its transport.
__aenter__() -> Self
async
¶
Enter the composed transport and return this transport.
__aexit__(exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: TracebackType | None = None) -> None
async
¶
Exit the composed transport, passing on any exception details.
__init__(*, retry: tenacity.AsyncRetrying, transport: httpx2.AsyncBaseTransport, **kwargs: dict[str, object]) -> None
¶
aclose() -> None
async
¶
Close the composed transport.
create(policy: RetryPolicy | None = None, transport: httpx2.AsyncBaseTransport | None = None, **kwargs: Unpack[HTTPX2HTTPTransportKeywordArguments]) -> AsyncTenaciousTransport
classmethod
¶
Create an instance of an asynchronous tenacious (retrying) transport.
This factory method constructs the instance with an underlying
httpx2.AsyncHTTPTransport.
That transport is passed any additional keyword arguments.
The retry policy creates the tenacity retrying instance. The default
SmartRetryPolicy retries requests when there are server-side issues
and will either wait the time set in a Retry-After response header or use a
random exponential backoff.
The returned transport owns the underlying transport, including one passed in
as transport, and closes it when it is closed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
RetryPolicy | None
|
The retry policy. Defaults to |
None
|
transport
|
AsyncBaseTransport | None
|
Pass an asynchronous transport instance to handle requests instead of the default one. |
None
|
**kwargs
|
Unpack[HTTPX2HTTPTransportKeywordArguments]
|
Additional keyword arguments are used in the construction of an
|
{}
|
Returns:
| Type | Description |
|---|---|
AsyncTenaciousTransport
|
A default instance of the class created from the given arguments. |
handle_async_request(request: httpx2.Request) -> httpx2.Response
async
¶
Handle an asynchronous request with retrying.
HTTPX2HTTPTransportKeywordArguments
¶
Bases: TypedDict
Keyword arguments for the sync and async httpx2 HTTPTransport constructor.