How to Fix TimeoutError in Python Requests
In this tutorial, you'll learn about How to Fix TimeoutError in Python Requests. We cover key concepts, practical examples, and best practices.
Python raises TimeoutError when a network request exceeds the maximum allowed wait time without receiving a response.
The Wrong Way
import requests
response = requests.get("http://slow-server.example.com")
print(response.text)
This produces (after hanging for a long time):
Traceback (most recent call last):
File "script.py", line 3, in <module>
response = requests.get("http://slow-server.example.com")
TimeoutError: The read operation timed out
The Right Way
Set an explicit timeout on every request:
import requests
try:
response = requests.get("http://slow-server.example.com", timeout=5)
print(response.text)
except requests.Timeout:
print("Request timed out after 5 seconds")
Output:
Request timed out after 5 seconds
Step-by-Step Fix
1. Set connect and read timeouts separately
import requests
timeout = (3.05, 10) # connect timeout, read timeout
try:
response = requests.get("http://example.com", timeout=timeout)
except requests.Timeout:
print("Request timed out")
2. Use a session with default timeout
import requests
from requests.adapters import HTTPAdapter
session = requests.Session()
session.mount('https://', HTTPAdapter(max_retries=3))
try:
response = session.get("http://example.com", timeout=5)
except requests.Timeout:
print("Request timed out")
3. Add retry logic for transient timeouts
import time
import requests
def fetch_with_retry(url, timeout=5, retries=3):
for attempt in range(retries):
try:
return requests.get(url, timeout=timeout)
except requests.Timeout:
if attempt < retries - 1:
time.sleep(2 ** attempt)
else:
print("All retries failed")
return None
4. Use asyncio with timeouts for concurrent requests
import asyncio
import aiohttp
async def fetch(session, url):
try:
async with session.get(url, timeout=aiohttp.ClientTimeout(total=5)) as response:
return await response.text()
except asyncio.TimeoutError:
return "Timeout"
Prevention Tips
- Always set
timeouton every HTTP request, including connect and read phases. - Use a session with retry adapters for resilient network code.
- Monitor server response times to set appropriate timeouts.
- Use circuit breaker patterns for external service calls.
- Log timeouts with full URL and timing details for debugging.
Common Mistakes with timeouterror
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro