Timeout in Python Requests
If you have worked with Python requests library, you might have encountered a situation where your request takes too long to get a response or the server does not give a response at all. This can be a frustrating experience, especially when you have a deadline to meet. In such situations, the use of timeout can be handy.
What is Timeout?
Timeout is the duration of time that a request will wait for a response from the server before it times out. It is measured in seconds.
How to Set Timeout in Python Requests
Timeout can be set using the timeout
parameter of the requests.get()
or requests.post()
method. Here is an example:
import requests
resp = requests.get('https://www.example.com', timeout=5)
In the above code, timeout=5
sets the timeout to 5 seconds. If the server does not respond within 5 seconds, a TimeoutError
will be raised.
Multiple Ways to Set Timeout
There are multiple ways to set timeout in Python requests:
- Global Timeout: You can set a global timeout for all requests made using requests library by setting the
timeout
parameter in theSession()
object. Example:
import requests
s = requests.Session()
s.timeout = 5
resp = s.get('https://www.example.com')
- Per-Request Timeout: You can set timeout on a per-request basis by setting the
timeout
parameter in theget()
orpost()
method. Example:
import requests
resp = requests.get('https://www.example.com', timeout=5)
- Connection Timeout: You can also set a separate timeout for establishing a connection to the server using the
connect_timeout
parameter. Example:
import requests
resp = requests.get('https://www.example.com', timeout=(5, 10))
In the above code, (5, 10)
sets the connection timeout to 5 seconds and the response timeout to 10 seconds. This means that if the server does not respond within 10 seconds after the connection is established, a TimeoutError
will be raised.