classSession#

class Session(
user_agent: str = 'modsmith/0.1.1 (https://github.com/PaPa-jun/Modsmith)',
attempts: int = 4,
backoff: float = 1.0,
timeout: tuple[float, float] = (10.0, 60.0),
)#

HTTP client with retries. Safe to share between threads.

Each thread gets its own connection pool. Use it as a context manager, or call close when you are done.

Parameters:
  • user_agent (str) – The User-Agent header sent with every request.

  • attempts (int) – How many times to try each request.

  • backoff (float) – Seconds to wait before the first retry. Doubles on each retry.

  • timeout (tuple[float, float]) – The connect and read timeouts in seconds.

close() → None#

Close the connections of every thread.

The session stays usable and reconnects on the next request.

property http: Session#

The calling thread’s requests.Session, created on first use.

wait(
attempt: int,
delay: float | None = None,
) → None#

Sleep before a retry.

Parameters:
  • attempt (int) – The zero-based index of the retry.

  • delay (float | None) – Seconds the server asked for, instead of the normal backoff.

request(
method: str,
url: str,
*,
accept: Collection[int] = (),
**kwargs: Any,
) → Response#

Send a request, retrying transient failures.

Retries stop once a response has been accepted, so reading a streamed body is not covered. A delay in Retry-After is respected, up to one minute.

Parameters:
Returns:

A successful response, or one with a status in accept.

Raises:

NetworkError – The last attempt failed or returned an error status.

Return type:

Response

get_json(
url: str,
**kwargs: Any,
) → Any#

Send a GET request and decode the JSON response.

Parameters:
Returns:

The decoded body.

Raises:

NetworkError – The request failed or the body is not JSON.

Return type:

Any

post_json(
url: str,
**kwargs: Any,
) → Any#

Send a POST request and decode the JSON response.

Parameters:
Returns:

The decoded body.

Raises:

NetworkError – The request failed or the body is not JSON.

Return type:

Any

stream(
url: str,
headers: Mapping[str, str] | None = None,
*,
accept: Collection[int] = (),
) → Response#

Open a streaming GET request, with the same retries as request.

Failures while reading the body are not retried, because the caller has to decide how to resume.

Parameters:
  • url (str) – The URL.

  • headers (Mapping[str, str] | None) – Extra request headers.

  • accept (Collection[int]) – Error statuses to return instead of raising.

Returns:

The open response. Use it as a context manager.

Raises:

NetworkError – The last attempt failed or returned an error status.

Return type:

Response