python requests default timeout

Python Requests Default Timeout

If you are working with Python requests module to make HTTP requests, you might want to set a timeout for your requests to prevent them from running indefinitely. When you make a request using requests module, it waits for the server to respond. If the server doesn't respond in a certain amount of time, it will raise a timeout error.

By default, requests module doesn't have any timeout set. However, you can set a custom timeout for your requests.

Setting a Timeout

You can set a timeout for your requests by passing the timeout parameter when making a request. The timeout parameter is the number of seconds to wait for a response. For example:


import requests

response = requests.get('https://example.com', timeout=5)
print(response.content)
  

In this example, we are setting a timeout of 5 seconds for our request to example.com. If the server doesn't respond within 5 seconds, a timeout error will be raised.

Default Timeout

If you want to set a default timeout for all your requests, you can do so by using the session object. A session object allows you to persist certain parameters across requests.

You can create a session object and set a default timeout for it:


import requests

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

response = session.get('https://example.com')
print(response.content)
  

In this example, we are creating a session object and setting its timeout to 5 seconds. Now, when we make a request using the session object, it will use the default timeout of 5 seconds.

Conclusion

Setting a timeout for your requests is important to prevent them from running indefinitely. You can set a custom timeout for each request or set a default timeout for all your requests using a session object.