Setting Timeout for Python Requests

To set a timeout for the Python Requests library, you can pass the "timeout" parameter for GET, POST, PUT, HEAD, and DELETE methods. The "timeout" parameter allows you to select the maximum time (in seconds) for the request to complete. By default, requests do not have a timeout unless you explicitly specify one. Setting a timeout for requests is recommended to avoid waiting for hung requests indefinitely. If you want to wait for the request to complete no matter how long it takes, you can pass "None" for "timeout". In this Python Requests Timeout Example, we pass a timeout for a request to indicate how long to wait for the server response. Click Execute to run Python Requests Timeout Example online and see the result.
Setting Timeout for Python Requests Execute
import requests

r = requests.get('https://reqbin.com/echo', timeout=5)

print(f"Status Code: {r.status_code}")
Updated: Viewed: 22705 times

What is Python?

Python is an interpreted high-level programming language known for its clean, readable syntax, flexibility, and ease of use. Python is a popular language for many applications, including web development, scientific computing, data analysis, artificial intelligence, etc. Python supports several programming paradigms, such as object-oriented, imperative, and functional programming. Python can run on various platforms, including Windows, Linux, and macOS.

What is the Python Request Library?

Requests Library is a prevalent Library that makes it easy to send HTTP requests using POST, GET and DELETE methods. The Requests Library is based on the urllib3 library and conceals the complexity of making HTTP requests behind a simple API. The Requests Library automatically validates the server's SSL certificates and supports International Domain Names and session cookies. The Requests Library is not included in the Python distribution, but everyone uses it because the Python code for HTTP becomes short, simple, and straightforward.

What is a Timeout in Python?

Timeout in Python is a mechanism that limits the amount of time it takes for operations to execute in a program. In the Python Requests library, timeouts are used to determine how long to wait for a response from the server before a request is considered a failure. Setting timeouts is important when dealing with network requests, as the server may not respond to a request for a long time, which can cause the application to hang. In Python Requests, you can set timeouts on a per-request basis and globally for all requests within a session. Setting a Timeout allows the program to continue executing if the operation does not complete within the specified time. Timeouts are widely used in various Python libraries and modules such as "socket", "urllib", "requests", and others. They allow you to control timeouts at the code level, which improves program performance and predictability.

What timeouts can be set for the Python Requests Library?

The following are the different timeouts that can be set using the Python Requests Library:

  • timeout: the overall timeout for the request, which is the time the entire request must complete, including connection establishment, request transmission, and response receipt. The value of this timeout can be set by passing the "timeout" parameter to the requests.request() function:

    Python Requests Timeout Example
    import requests
    
    r = requests.get('https://reqbin.com/echo', timeout=5)
    
    print(f"Status Code: {r.status_code}")

  • connect timeout: the timeout for establishing a connection to the server. This timeout value can be set by passing the "timeout" parameter to the requests.request() function and setting the "connect" key to the desired timeout value:

    Python Requests Connect Timeout Example
    import requests
    
    r = requests.get('https://reqbin.com/echo', timeout=(5, None))
    
    print(f"Status Code: {r.status_code}")

  • read timeout: the timeout for waiting for a response from the server after the connection has been established. This timeout value can be set by passing the "timeout" parameter to the requests.request() function and setting the "read" key to the desired timeout value:

    Python Requests Read Timeout Example
    import requests
    
    r = requests.get('https://reqbin.com/echo', timeout=(None, 5))
    
    print(f"Status Code: {r.status_code}")

How to use a timeout for Python Requests?

You can use the 'timeout' option to set a timeout for Python Requests. The "timeout" parameter specifies the maximum time to wait for a response from the server. If no response is received within this time, the program will throw an exception (ConnectionError and ReadTimeout). By default, requests do not have a timeout unless you specify one explicitly.

Python Requests Timeout Example
import requests

try:
    response = requests.get('https://reqbin.com/echo', timeout=5)
    print(response.status_code)
except requests.exceptions.Timeout:
    print('The request timed out')

How to set connection and reading timeouts?

To set connection and read timeouts for an HTTP request in Python, you can pass a tuple containing two values to the "timeout" parameter, where the first value is the connection timeout (in seconds) and the second value is the timeout -reading out (in seconds).

Python Requests Setting Connection and Reading Timeouts
import requests

try:
    response = requests.get('https://reqbin.com/echo', timeout = (3, 5))
    print(response.status_code)
except requests.exceptions.Timeout:
    print("The request timed out")
except requests.exceptions.RequestException as e:
    print("An error occurred:", e)

Why is it important to set a reasonable timeout value?

Setting a reasonable timeout value in Python Requests depends on the specific task your program is performing and your performance and security requirements. It is generally recommended to set a timeout between 5 and 30 seconds for regular HTTP requests. If your program processes large amounts of data or performs complex operations, you may need to set a longer timeout. Thus, using timeouts in Python Requests is an excellent practice to keep your program stable, safe, and more efficient.

See also