Python Requests Timeout: What You Need to Know
If you are working with Python requests, you may encounter situations where you need to set a timeout for your requests. In simple terms, a timeout is the amount of time that you are willing to wait for a response from a server before giving up.
Setting a Timeout
The good news is that setting a timeout in Python requests is easy. You can specify a timeout by passing a value to the timeout
parameter in your request:
import requests
response = requests.get('https://www.example.com', timeout=5)
print(response.content)
In this example, we are setting a timeout of 5 seconds for our request to 'https://www.example.com'. If the server does not respond within 5 seconds, the request will be aborted and a timeout exception will be raised.
Timeout Types
There are two types of timeouts that you can set in Python requests:
- Connect Timeout: The amount of time that you are willing to wait for a connection to be established.
- Read Timeout: The amount of time that you are willing to wait for a response after a connection has been established.
You can set both types of timeouts by passing a tuple to the timeout
parameter:
import requests
response = requests.get('https://www.example.com', timeout=(2, 5))
print(response.content)
In this example, we are setting a connect timeout of 2 seconds and a read timeout of 5 seconds.
Handling Timeout Exceptions
If a timeout occurs, Python requests will raise a requests.exceptions.Timeout
exception. You can handle this exception like any other exception in Python:
import requests
try:
response = requests.get('https://www.example.com', timeout=5)
print(response.content)
except requests.exceptions.Timeout:
print('The request timed out')
In this example, we are using a try-except block to handle the Timeout
exception that may be raised if the request times out.
Conclusion
Setting timeouts for your Python requests is an important step to ensure that your application remains responsive and performs well. By using the timeout
parameter, you can easily set a timeout for your requests and handle any exceptions that may occur.