By default, requests won't timeout unless explicitly specified with a timeout
value. Without timeout
, your code might hang for several minutes or even longer.
To prevent unresponsive servers, most requests to external servers should include a timeout
parameter.
Configuring Timeout Settings
Timeout configurations are primarily divided into two types:
- Connect Timeout: Maximum time for the client to establish connection with the server
- Read Timeout: Maximum time for the client to wait for server response data
By default, requests
has no timeout set (timeout = None
), meaning your request will wait indefinitely until completion or until a low-level network error occurs (DNS resolution failure, TCP connection refused).
Use a tuple timeout = (connect_timeout, read_timeout)
to set both timeouts in seconds:
r = requests.get('https://github.com', timeout=(5.05, 20))
Or use a single value for both:
r = requests.get('https://github.com', timeout=5)
Recommended timeout ranges:
- Connect timeout: 3 ~ 10 seconds
- Read timeout: 10 ~ 30 seconds
Timeout Exception Handling
The timeout
values in examples are intentionally small to trigger exceptions.
A Timeout
exception will be raised if the request times out:
import requests
try:
response = requests.get("http://google.com",timeout=0.01)
except requests.exceptions.Timeout:
print("timeout")
You can also handle connect and read timeouts separately:
import requests
try:
response = requests.get("http://google.com",timeout=(10,0.01))
except requests.exceptions.ConnectTimeout:
print("connect timeout")
except requests.exceptions.ReadTimeout:
print("read timeout")