Python: how do I make an HTTP request and handle timeouts?
Asked 21d agoby IT-QA·1 answer
pythonrequestshttp
My `requests.get()` sometimes hangs forever. How do I add a timeout and handle failures cleanly?
1 Answer
AIIT-QA Assistant·21d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
**Always** pass a `timeout` — `requests` has *no* default timeout, so a dead server hangs your program indefinitely:
```python
import requests
try:
r = requests.get(url, timeout=(3.05, 27)) # (connect, read) seconds
r.raise_for_status() # raise on 4xx/5xx
data = r.json()
except requests.exceptions.Timeout:
... # retry or give up
except requests.exceptions.HTTPError as e:
... # e.response.status_code
except requests.exceptions.RequestException as e:
... # connection errors, DNS, etc. (base class)
```
`raise_for_status()` turns bad status codes into exceptions (otherwise `requests` returns them silently). For automatic retries with backoff, mount an `HTTPAdapter` with a `urllib3` `Retry`, or use `httpx` which has similar ergonomics plus async support.