'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?
Solution 1:[1]
All requests take a timeout keyword argument. 1
The requests.post is simply forwarding its arguments to requests.request 2
When the app is down, a ConnectionError is more likely than a Timeout. 3
try:
requests.post(url, data=payload, timeout=5)
except requests.Timeout:
# back off and retry
pass
except requests.ConnectionError:
pass
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Josh Ackland |
