how to set timeout in python requests

How to Set Timeout in Python Requests

If you're using Python Requests library to make HTTP requests, you may face some situations where the request takes too long to complete or the server doesn't respond at all. To avoid hanging your program indefinitely in such cases, you can set a timeout for your requests.

Method 1: Pass Timeout Parameter

You can specify the timeout for a request by passing the timeout parameter to the request method. The value of this parameter can be either a tuple or a float value.import requests # Timeout after 5 seconds response = requests.get('https://example.com', timeout=5) # Timeout after 2.5 seconds for connect and read operations separately response = requests.get('https://example.com', timeout=(2.5, 2.5))

In the first example, the request will timeout after 5 seconds if no response is received. In the second example, the connect and read operations will timeout separately after 2.5 seconds each.

Method 2: Set Default Timeout

You can also set a default timeout for all your requests using the timeout parameter of the Session object. This will apply to all requests made using this session unless you override it by passing a different value to the request method.import requests # Create session with default timeout of 5 seconds session = requests.Session() session.timeout = 5 # Make request with default timeout response = session.get('https://example.com') # Make request with custom timeout response = session.get('https://example.com', timeout=10)

In this example, the default timeout for all requests made using session is set to 5 seconds. The first request uses the default timeout, while the second request overrides it with a custom timeout of 10 seconds.