python requests module timeout

Python Requests Module Timeout

If you're working with the Requests module in Python, you may come across situations where the request takes too long to get a response. In order to handle these situations, Requests module provides a parameter called timeout.

Using Timeout Parameter

The timeout parameter is used to set the number of seconds a request should wait for a response. If the server doesn't respond within this time, the request will be aborted with a timeout error.

import requests

try:
    response = requests.get(url, timeout=5)
    response.raise_for_status()
    print(response.content)
except requests.exceptions.Timeout:
    print("Timeout occurred")
except requests.exceptions.RequestException as e:
    print(f"Error occurred: {e}")

In the above code snippet, we are making a GET request to a URL and setting the timeout parameter to 5 seconds. If the server doesn't respond within this time, a Timeout exception will be raised and we will print "Timeout occurred".

Other Ways to Handle Timeouts

  • We can also set a global timeout for all requests by setting the timeout parameter in the session object.
  • We can use the Retry object to automatically retry failed requests with a timeout.
  • Another way is to use the signal module to set a timeout for the entire script.

It's important to handle timeouts properly in order to avoid unresponsive scripts or applications. By using the timeout parameter, we can gracefully handle these situations and provide a better user experience.