Python requests

Sessions, timeouts, retries, streaming downloads and the mistakes that hang production.

Beginner
Key PointsNo timeout means an infinite hang — always pass `timeout=(connect, read)` and call `raise_for_status()`.

GET and POST

Python
import requests

resp = requests.get("https://api.example.com/users",
                    params={"page": 1, "size": 20},
                    headers={"Authorization": "Bearer TOKEN"},
                    timeout=(3, 10))
resp.raise_for_status()
data = resp.json()

r = requests.post("https://api.example.com/users",
                  json={"name": "alice"},      # 自动 JSON 序列化 + Content-Type
                  timeout=10)
resp.json() raises if the body is not JSON. Check resp.headers['content-type'] first when scraping HTML pages.

Sessions

A Session reuses the TCP connection and keeps cookies and default headers — 2-5x faster for repeated calls to the same host.

Python
s = requests.Session()
s.headers.update({"User-Agent": "myapp/1.0", "Authorization": "Bearer TOKEN"})

for page in range(1, 6):
    r = s.get(f"https://api.example.com/items?page={page}", timeout=10)
    r.raise_for_status()
    print(len(r.json()["items"]))

Retries

Python
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

retry = Retry(total=3, backoff_factor=0.5,
              status_forcelist=[429, 500, 502, 503, 504],
              allowed_methods=["GET", "POST"])

s = requests.Session()
s.mount("https://", HTTPAdapter(max_retries=retry))

Streaming Downloads

Python
with requests.get(url, stream=True, timeout=30) as r:
    r.raise_for_status()
    with open("big.zip", "wb") as f:
        for chunk in r.iter_content(chunk_size=8192):
            f.write(chunk)

Status Codes

CodeMeaningAction
2xxSuccessParse body
301 / 302RedirectFollowed automatically
400Bad requestFix payload, do not retry
401 / 403Auth failureRefresh token
429Rate limitedBack off per Retry-After
5xxServer errorRetry with backoff
requests is synchronous. In async code use httpx.AsyncClient — calling requests inside a coroutine blocks the whole event loop.

Friends & Partners