Python

requests Session with Retry + Timeouts

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A pre-configured requests.Session that auto-retries 5xx + connect errors with exponential backoff, applies a default timeout, and uses connection pooling. Use this everywhere instead of bare requests.get().
Python
Raw
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

def make_session(
    retries: int = 5,
    backoff: float = 0.3,
    timeout: float = 10,
) -> requests.Session:
    s = requests.Session()
    retry = Retry(
        total=retries,
        backoff_factor=backoff,
        status_forcelist=(429, 500, 502, 503, 504),
        allowed_methods=frozenset(["GET", "POST", "PUT", "DELETE", "PATCH"]),
        raise_on_status=False,
    )
    adapter = HTTPAdapter(max_retries=retry, pool_connections=10, pool_maxsize=10)
    s.mount("https://", adapter)
    s.mount("http://", adapter)
    # Stash default timeout on the session — apply it manually in each call.
    s.request = lambda *a, **kw: requests.Session.request(s, *a, timeout=kw.pop("timeout", timeout), **kw)
    return s

api = make_session()
r = api.get("https://api.example.com/users")
r.raise_for_status()
print(r.json())
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.