Requests timeout in Python

When you make requests to an external service, you need to wait for the response before continuing. If you don’t set a timeout, the requests will wait indefinitely on the response.

You should always use the timeout parameter in your code. Otherwise, the user experience will suffer, or your application will hang.

After you set the timeout parameter, the program will raise the exception, if the server hasn’t received any answer from the server for the number of seconds set in timeout.

Setting request timeout

Let’s first try the code without request timeout. First, you have to import requests.

Now, if you run the code, the program, unless the site is down, will return the success status.

Let’s add the timeout parameter to be sure that the program will finish the request if there is no response.

You can also use floats with the timeout parameter.

If you run the code, the request will timeout after 3.15 seconds.

Timeout parameter types

As I wrote before, you can use int and float values as the timeout parameter. In addition to that, you can also use tuples.

The tuple comes with two elements. The first element is the time to establish a connection with the remote server, and the second parameter is the time it will wait for a response from the server after the connection was established.

In our case, the program will wait 3 seconds to establish a connection, and if this successful, it will wait for another 8 for the server response.

Timeout exceptions

We always need to remember that if something bad can go wrong, it will. We have to be prepared for bad things to happen.

That’s why it’s a good idea to handle exceptions. In our case, it will be the timeout exception.

First, you have to add the request.exceptions module and import Timeout.

If you run this code and everything goes well, you will get the response:

If you lower the timeout value and run the code, you are going to get: