python requests module default timeout

Python Requests Module Default Timeout

As a programmer, using a programming language like Python, you may have to send HTTP requests to external servers to retrieve data or interact with APIs. In order to do so, you can use the Python Requests module, which is a popular package that makes it easy to send HTTP requests in Python.

One of the features of the Requests module is the ability to set a timeout for the request. By default, if you don't set a timeout explicitly, the request will not time out and will wait indefinitely for a response from the server. This can be problematic in certain situations, such as when the server is down or unresponsive. Setting a timeout ensures that your program will not hang indefinitely waiting for a response.

Setting a Timeout

To set a timeout for your request, you can pass a timeout parameter to the request method:


import requests

response = requests.get('http://example.com', timeout=5)

In this example, we're setting the timeout to 5 seconds. If the server doesn't respond within 5 seconds, the request will raise a Timeout exception.

Timeout Units

The timeout parameter value can be specified in seconds or as a tuple of (connect timeout, read timeout) values. Connect timeout is the time taken to establish a connection with the server and read timeout is the time taken to get the response from the server.


import requests

# Set connect timeout to 2.5 seconds and read timeout to 5 seconds
response = requests.get('http://example.com', timeout=(2.5, 5))

In this example, we're setting the connect timeout to 2.5 seconds and the read timeout to 5 seconds.

Setting a Default Timeout

If you're making many requests and want to set a default timeout for all of them, you can use the Session object provided by the Requests module:


import requests

# Create a session object
session = requests.Session()

# Set the default timeout to 5 seconds for all requests made with this session
session.request('GET', 'http://example.com', timeout=5)

In this example, we're creating a session object and setting the default timeout to 5 seconds for all requests made with that session. This means that we don't have to specify the timeout parameter for each request individually.

Conclusion

The Python Requests module makes it easy to send HTTP requests in Python. By setting a timeout for your requests, you can ensure that your program doesn't hang indefinitely waiting for a response. You can set the timeout parameter explicitly for each request or set a default timeout for all requests made with a session object.