timeout parameter in requests python

Understanding the Timeout Parameter in Python Requests Library

The timeout parameter in the Python Requests library specifies the maximum amount of time to wait for a response from the server. This parameter is useful when you are making requests to external API endpoints or other web services that may take a long time to respond. Setting a timeout value ensures that your program does not hang indefinitely, waiting for a response that may never arrive.

Setting Timeout Parameter in Python Requests

To set a timeout value in your Python requests, you can pass the timeout parameter to the requests.get() method or any other HTTP method. The default value for this parameter is None, which means that the request will not timeout until a response is received or an exception is raised.


import requests

url = "https://api.example.com/users"

response = requests.get(url, timeout=5)

print(response.status_code)
  

The code above sends a GET request to the specified URL with a timeout of 5 seconds. If the server does not respond within 5 seconds, a Timeout exception will be raised.

Timeout Exception Handling

If a request times out, Python Requests raises a Timeout exception. To handle this exception, you can use a try-except block to catch it and take appropriate action.


import requests

url = "https://api.example.com/users"

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

The code above sets a timeout of 5 seconds for the GET request to the specified URL. If the request times out, a message will be printed to the console.

Setting Global Timeout Value in Python Requests

If you want to set a default timeout value for all requests made using the Python Requests library, you can use the timeout parameter in the requests.Session() object.


import requests

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

response1 = session.get("https://api.example.com/users")
response2 = session.get("https://api.example.com/posts")

print(response1.status_code)
print(response2.status_code)
  

The code above creates a Session object with a default timeout of 10 seconds. This timeout will be applied to all requests made using this session object, unless overridden by a specific timeout value passed to the request method.