Build a reusable `requests.Session` with bounded retries for transient GET failures, without retrying every possible HTTP error.
Answer
Configure a Session with an HTTPAdapter backed by urllib3 `Retry`. Bound the retry count, limit retries to idempotent methods such as GET, choose only transient status codes like 429/502/503/504, and set a request timeout separately because retry count does not cap the duration of an individual attempt. This gives explicit, reviewable resilience instead of a broad retry loop around every exception.
Strong answer includes
- uses Session plus HTTPAdapter/Retry
- retries only bounded transient/idempotent cases
- sets a per-request timeout separately
Practical example
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry = Retry(
total=3,
backoff_factor=0.25,
status_forcelist=(429, 502, 503, 504),
allowed_methods={"GET"},
)
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))
response = session.get("https://api.example.test/health", timeout=5)
response.raise_for_status()The adapter controls which responses may be retried and how many times; the timeout independently bounds each network attempt.
Expected result: A successful response returns normally; exhausted retries or a final error status raises through the normal requests/urllib3 error path.