Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP requests.post timeout

In my code below, I use requests.post. What are the possibilities to simply continue if the site is down?

I have the following code:

def post_test():      import requests      url = 'http://example.com:8000/submit'     payload = {'data1': 1, 'data2': 2}     try:         r = requests.post(url, data=payload)     except:         return   # if the requests.post fails (eg. the site is down) I want simly to return from the post_test(). Currenly it hangs up in the requests.post without raising an error.     if (r.text == 'stop'):         sys.exit()  # I want to terminate the whole program if r.text = 'stop' - this works fine. 

How could I make the requests.post timeout, or return from post_test() if example.com, or its /submit app is down?

like image 713
Zorgmorduk Avatar asked Feb 10 '19 18:02

Zorgmorduk


People also ask

How long is HTTP request timeout?

The default value is 100,000 milliseconds (100 seconds).

What is HTTP request timeout?

The HyperText Transfer Protocol (HTTP) 408 Request Timeout response status code means that the server would like to shut down this unused connection. It is sent on an idle connection by some servers, even without any previous request by the client.

How do I set timeout in request?

To set a timeout in Python Requests, you can pass the "timeout" parameter for GET, POST, PUT, HEAD, and DELETE methods. The "timeout" parameter allows you to select the maximum time (number of seconds) for the request to complete. By default, requests do not have a timeout unless you explicitly specify one.


1 Answers

Use the timeout parameter:

r = requests.post(url, data=payload, timeout=1.5) 

Note: timeout is not a time limit on the entire response download; rather, an exception is raised if the server has not issued a response for timeout seconds (more precisely, if no bytes have been received on the underlying socket for timeout seconds). If no timeout is specified explicitly, requests do not time out.

like image 64
JacobIRR Avatar answered Sep 28 '22 01:09

JacobIRR