timeout in requests python

Timeout in Requests Python

Have you ever encountered a situation where your Python script makes a request to an external server and it takes too long to respond? This can be a frustrating situation, especially if your program is designed to run continuously and relies on the external server to provide data. Fortunately, the requests library in Python provides a way to set a timeout for requests. A timeout is the amount of time that the library will wait for a response from the server before giving up.

Setting Timeout in Requests Python

To set a timeout in requests, you can simply pass the timeout parameter to the get() or post() method. The value of the timeout parameter is in seconds. For example, if you want to set a timeout of 5 seconds for a request, you can do the following:


import requests

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

In the above example, if the server takes more than 5 seconds to respond, an exception will be raised. You can catch this exception using a try-except block.

Handling Timeout Exceptions in Requests Python

When a timeout exception is raised in requests, it is an instance of the requests.exceptions.Timeout class. You can catch this exception using a try-except block and handle it accordingly. For example:


import requests
from requests.exceptions import Timeout

url = 'http://example.com'

try:
    response = requests.get(url, timeout=5)
except Timeout:
    print('The request timed out')
  

In the above example, if the server takes more than 5 seconds to respond, the message "The request timed out" will be printed.

Multiple Ways to Set Timeout in Requests Python

Apart from passing the timeout parameter to the get() or post() method, there are other ways to set a timeout in requests. For example:

  • You can set a default timeout for all requests by setting the timeout attribute of the Session object. This will override any timeouts set for individual requests. For example:

import requests

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

response = session.get('http://example.com')
print(response.content)
        
  • You can use a context manager to set a timeout for a block of code that makes requests. For example:

import requests

url = 'http://example.com'

with requests.Session() as session:
    session.timeout = 5
    response = session.get(url)
    print(response.content)
        

These are just some of the ways you can set a timeout in requests. Depending on your specific use case, one method may be more appropriate than others.