What is the recommended way to handle exceptions and timeouts with Python Requests? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

What is the recommended way to handle exceptions and timeouts with Python Requests?

message-square
0

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

  • requests hangs forever by default if timeout= is omitted:
    • Unlike many HTTP clients, requests.get(url) defaults to timeout=None, meaning a stalled socket or unresponsive upstream server can block a worker thread indefinitely. Always pass a scalar timeout=10 or a 2-tuple timeout=(3.05, 10) (setting connect timeout slightly above a 3-second TCP SYN retransmission window avoids premature connect aborts).
  • Important nuance: timeout is NOT a total wall-clock cap for large downloads:
    • read_timeout measures 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 trigger ReadTimeout even if a download takes hours; enforce a hard wall-clock deadline with time.monotonic() when streaming large files (stream=True).
  • requests does NOT raise exceptions on 404 or 500 responses automatically:
    • requests.get(...) returns a normal Response object even when response.status_code == 500. Always call response.raise_for_status() before calling response.json() (and guard response.json() with requests.exceptions.JSONDecodeError if an upstream gateway might return HTML on an error page).
  • Exception inheritance order matters (Timeout and ConnectionError are subclasses of RequestException):
    • Catch specific subclasses (ConnectTimeout, ReadTimeout, Timeout, HTTPError, ConnectionError) above except requests.exceptions.RequestException:—if RequestException comes first, none of the specific handlers below it will ever execute.
    • Note that SSLError inherits from ConnectionError, and both ConnectTimeout and ReadTimeout inherit from Timeout (which inherits from RequestException).
  • Be careful retrying POST / PATCH requests (allowed_methods):
    • By default in urllib3 Retry, POST is excluded from allowed_methods because retrying a timed-out POST /payments request can create duplicate charges unless your API supports an Idempotency-Key header.

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.