Always pass an explicit timeout=(connect_timeout, read_timeout) tuple (such as timeout=(3.05, 10)) to every requests call, invoke response.raise_for_status() immediately so HTTP 4xx/5xx responses raise HTTPError, and catch requests.exceptions.Timeout, requests.exceptions.HTTPError, requests.exceptions.ConnectionError, and the base requests.exceptions.RequestException—while configuring urllib3.util.retry.Retry on a requests.Session() when transient network errors or 429/502/503/504 responses should retry automatically.
Basic Example
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def create_retrying_session() -> requests.Session:
session = requests.Session()
retry_strategy = Retry(
total=3,
backoff_factor=0.5, # Sleeps 0.5s, 1.0s, 2.0s between retries
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["HEAD", "GET", "OPTIONS"], # Never blindly retry non-idempotent POSTs
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("https://", adapter)
session.mount("http://", adapter)
return session
# 1. Recommended: Always pass `timeout=(connect, read)` and call `raise_for_status()`
try:
with create_retrying_session() as session:
response = session.get(
"[https://api.example.com/v1/orders](https://api.example.com/v1/orders)",
timeout=(3.05, 10), # (connect timeout in seconds, read timeout in seconds)
)
response.raise_for_status() # Raises `HTTPError` for 4xx / 5xx status codes
payload = response.json()
except requests.exceptions.ConnectTimeout:
print("TCP connection timed out before reaching the server.")
except requests.exceptions.ReadTimeout:
print("Server accepted the connection but took too long to send data.")
except requests.exceptions.HTTPError as err:
print(f"HTTP error {err.response.status_code}: {err.response.text[:200]}")
except requests.exceptions.ConnectionError:
print("DNS failure, refused connection, or network unreachable.")
except requests.exceptions.RequestException as err:
# Base catch-all for every exception `requests` can raise (TooManyRedirects, InvalidURL, etc.)
print(f"Unexpected requests failure: {err}")
Key Details & Edge Cases
requestshangs forever by default iftimeout=is omitted:- Unlike many HTTP clients,
requests.get(url)defaults totimeout=None, meaning a stalled socket or unresponsive upstream server can block a worker thread indefinitely. Always pass a scalartimeout=10or a 2-tupletimeout=(3.05, 10)(setting connect timeout slightly above a 3-second TCP SYN retransmission window avoids premature connect aborts).
- Unlike many HTTP clients,
- Important nuance:
timeoutis NOT a total wall-clock cap for large downloads:read_timeoutmeasures the maximum silence gap between consecutive bytes received from the server, not total transfer time. A slow-trickle server sending 1 byte per second will never triggerReadTimeouteven if a download takes hours; enforce a hard wall-clock deadline withtime.monotonic()when streaming large files (stream=True).
requestsdoes NOT raise exceptions on404or500responses automatically:requests.get(...)returns a normalResponseobject even whenresponse.status_code == 500. Always callresponse.raise_for_status()before callingresponse.json()(and guardresponse.json()withrequests.exceptions.JSONDecodeErrorif an upstream gateway might return HTML on an error page).
- Exception inheritance order matters (
TimeoutandConnectionErrorare subclasses ofRequestException):- Catch specific subclasses (
ConnectTimeout,ReadTimeout,Timeout,HTTPError,ConnectionError) aboveexcept requests.exceptions.RequestException:—ifRequestExceptioncomes first, none of the specific handlers below it will ever execute. - Note that
SSLErrorinherits fromConnectionError, and bothConnectTimeoutandReadTimeoutinherit fromTimeout(which inherits fromRequestException).
- Catch specific subclasses (
- Be careful retrying
POST/PATCHrequests (allowed_methods):- By default in
urllib3Retry,POSTis excluded fromallowed_methodsbecause retrying a timed-outPOST /paymentsrequest can create duplicate charges unless your API supports anIdempotency-Keyheader.
- By default in
Comparison of Core requests.exceptions Hierarchy & Handling
| Exception Class | Parent Class | Trigger Condition | Retryable? | Best Action |
|---|---|---|---|---|
ConnectTimeout |
Timeout $\rightarrow$ RequestException |
TCP handshake did not complete within connect_timeout seconds. |
Yes (safe even for POST—server never received payload) |
Retry with exponential backoff or fail fast to a backup host. |
ReadTimeout |
Timeout $\rightarrow$ RequestException |
Server connected, but sent no bytes within read_timeout seconds. |
Idempotent only (GET/HEAD/PUT) |
Retry GETs; for POST, verify server state or use an idempotency key before retrying. |
ConnectionError (includes SSLError) |
RequestException |
DNS lookup failure, connection refused/reset, or TLS certificate mismatch. | Transient network only (never retry SSLError) |
Log DNS/TLS details; retry only transient socket resets. |
HTTPError |
RequestException |
response.raise_for_status() called on a 4xx or 5xx status code. |
429, 502, 503, 504 only |
Inspect err.response.status_code and Retry-After header; do not retry 400/401/403/404. |
RequestException |
OSError (IOError) |
Catch-all base class for every requests error (TooManyRedirects, InvalidURL, etc.). |
Depends on subclass | Use as the final fallback except handler around external HTTP calls. |
You must log in or register to comment.
