Networking Errors and Timeouts
Common networking failures
- Timeouts: server too slow
- Connection errors: server down, wrong port
- DNS errors: domain name canβt be resolved
- HTTP errors: 4xx/5xx responses
requests exceptions
requests_errors.py
import requests
try:
r = requests.get("https://httpbin.org/delay/10", timeout=2)
r.raise_for_status()
print(r.text[:100])
except requests.Timeout:
print("Timed out")
except requests.ConnectionError:
print("Connection error")
except requests.HTTPError as e:
print("HTTP error:", e)
except requests.RequestException as e:
print("Other request error:", e)requests_errors.py
import requests
try:
r = requests.get("https://httpbin.org/delay/10", timeout=2)
r.raise_for_status()
print(r.text[:100])
except requests.Timeout:
print("Timed out")
except requests.ConnectionError:
print("Connection error")
except requests.HTTPError as e:
print("HTTP error:", e)
except requests.RequestException as e:
print("Other request error:", e)Add a timeout everywhere
- Always set
timeout=timeout= - Combine with retries if needed
Basic backoff idea
backoff.py
import time
import requests
url = "https://httpbin.org/status/503"
wait = 1
for attempt in range(4):
try:
r = requests.get(url, timeout=5)
r.raise_for_status()
print("success")
break
except requests.RequestException:
print("failed, sleeping", wait)
time.sleep(wait)
wait *= 2backoff.py
import time
import requests
url = "https://httpbin.org/status/503"
wait = 1
for attempt in range(4):
try:
r = requests.get(url, timeout=5)
r.raise_for_status()
print("success")
break
except requests.RequestException:
print("failed, sleeping", wait)
time.sleep(wait)
wait *= 2Tip
For production-grade retries, use a library or configure a session with retry adapters.
π§ͺ Try It Yourself
Exercise 1 β GET Request
Exercise 2 β POST with JSON
Exercise 3 β Handle Timeout
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
