requests timeout

September 21, 2020



https://requests.readthedocs.io/en/master/user/advanced/#timeouts

python requests - Advanced Usage

I more or less copied this bit from the above link. But this reflects the importance of timeouts when doing requests in python. Python mostly works synchronously and without the use of timeouts, an application can be unresponsive possibly for minutes.

Making requests with the python requests module defaults to:

timeout=None

This means the request finishes when a response comes in. In some cases this can be useful (slow servers).

There are 2 kinds of timeout the requests module supports:

The connect timeout is given in seconds and is meant for the client to establish a connection to a remote machine.

The read timeout is given in seconds as well and defines for how long the client will wait for the server to send a response.

Setting the same timeout for both (connect and read timeout) can be achieved with a single value:

timeout=5

Setting the timeouts separately is done using a tuple (first connect then read timeout):

timeout=(3.05, 27)

Full example:

import requests
from requests.exceptions import Timeout

try:
    with requests.Session() as session:
        response = sesson.get('https://github.com', timeout=1)
except Timeout:
    print('The request timed out')
else:
    print('The request did not time out')