Networking Errors and Timeouts
Common networking failures
Section titled “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
Section titled “requests exceptions”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
Section titled “Add a timeout everywhere”- Always set
timeout= - Combine with retries if needed
Basic backoff idea
Section titled “Basic backoff idea”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 *= 2For production-grade retries, use a library or configure a session with retry adapters.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – GET Request
Section titled “Exercise 1 – GET Request”Exercise 2 – POST with JSON
Section titled “Exercise 2 – POST with JSON”Exercise 3 – Handle Timeout
Section titled “Exercise 3 – Handle Timeout”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading