python requests timeout default

Python Requests Timeout Default

If you are working with web APIs using Python, you might have come across the requests library. It's a popular Python library for making HTTP requests. One of the most important aspects of web APIs is network latency, which can cause requests to take a long time to complete or even fail. To deal with such situations, requests library provides a timeout parameter.

Default Timeout Value

The default timeout value for requests library is None, which means it will wait indefinitely until the server responds. This can be a problem because it can cause your program to hang indefinitely. Therefore, it's always better to set a timeout value.

Setting Timeout Value

You can set the timeout value while making the request by passing it as a parameter to the request method:

import requests

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

print(response.status_code)

In the above code, we have set the timeout value to 5 seconds. If the server doesn't respond within 5 seconds, a Timeout exception will be raised.

Global Timeout Value

If you want to set a global timeout value for all requests made by your program, you can do so by setting the timeout attribute on the Session object:

import requests

session = requests.Session()
session.timeout = 5

response = session.get('http://example.com')

print(response.status_code)

In the above code, we have set a global timeout value of 5 seconds for all requests made using the session object.