python requests timeout example

Python Requests Timeout Example

Python Requests is a popular library for sending HTTP requests in Python. It allows you to send HTTP/1.1 requests using Python. Timeout is an important parameter when sending requests, as it determines how long the client will wait for the server to respond before giving up. In this blog post, we will discuss how to set timeout in Python Requests library.

How to set timeout in Python Requests:

There are two ways to set timeout in Python Requests:

  • Timeout parameter in request method: The simplest way to set timeout in Python Requests is by passing a timeout parameter to the request method. The value of the timeout parameter is in seconds. If the server does not respond within the specified timeout period, a Timeout exception is raised.
  • Session object: You can also set a default timeout for all requests made using a session object.

Example 1: Setting timeout in request method


import requests

try:
    response = requests.get('http://httpbin.org/delay/5', timeout=2)
    print(response.content)
except requests.exceptions.Timeout as e:
    print("Timeout Error:", e)

In this example, we are sending a GET request to a test server which delays the response by 5 seconds. We have set the timeout parameter to 2 seconds. So, if the server does not respond within 2 seconds, a Timeout exception is raised.

Example 2: Setting default timeout using Session object


import requests

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

try:
    response = session.get('http://httpbin.org/delay/5')
    print(response.content)
except requests.exceptions.Timeout as e:
    print("Timeout Error:", e)

In this example, we are creating a session object and setting a default timeout of 2 seconds. Now, all requests made using this session object will have a timeout of 2 seconds. If the server does not respond within 2 seconds, a Timeout exception is raised.

These are the two ways to set timeout in Python Requests. You can choose the method that suits your use case the best.