Zor*_*duk 9 python python-3.x python-requests
在下面的代码中,我使用requests.post。如果站点宕机,继续运行的可能性有哪些?
我有以下代码:
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.
Run Code Online (Sandbox Code Playgroud)
如果example.com或其/ submit应用程序关闭,我如何使request.post超时,或者从post_test()返回?
Jac*_*IRR 15
使用timeout参数:
r = requests.post(url, data=payload, timeout=1.5)
Run Code Online (Sandbox Code Playgroud)
注意:
timeout整个响应下载没有时间限制;相反,如果服务器timeout几秒钟未发出响应(更确切地说,如果几秒钟内未在基础套接字上接收到任何字节),则会引发异常timeout。如果未明确指定超时,则请求不会超时。
所有请求都带有超时关键字参数。1个
的requests.post是简化转发其参数requests.request 2
当应用关闭时,出现的可能性ConnectionError大于Timeout。3
try:
requests.post(url, data=payload, timeout=5)
except requests.Timeout:
# back off and retry
pass
except requests.ConnectionError:
pass
Run Code Online (Sandbox Code Playgroud)