HTTP请求.post超时

50
在下面的代码中,我使用了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.

如果example.com或其/submit应用程序出现故障,我该如何使requests.post超时或从post_test()返回?

2个回答

83

使用timeout参数:

r = requests.post(url, data=payload, timeout=1.5)
注意: timeout 不是整个响应下载的时间限制;相反,如果服务器在timeout秒内未发出响应(更准确地说,如果底层套接字未接收到任何字节timeout秒),则会引发异常。 如果未明确指定超时,则请求不会超时。

你还确定如果没有明确指定超时时间,请求不会超时吗?事实是我试过了,它们似乎会自动超时! - Haris
1
它们不会因为Python而超时,而是因为服务器超时,这是您的代码无法控制的。 - JacobIRR
所以你的意思是,超时时间将从服务器在服务端收到请求开始计算?还是从客户端发出请求开始计算?我猜应该是从服务器收到请求开始计算。谢谢。 - turong
有趣的是:pylint会提示您超时,我想知道套接字函数是否可能根本没有超时。这意味着请求将始终超时。 - Nikolai Ehrhardt

30

所有请求都接受timeout关键字参数。1

requests.post只是将其参数转发给requests.request2

当应用程序停止运行时,比起超时,ConnectionError更有可能出现。3

try:
    requests.post(url, data=payload, timeout=5)
except requests.Timeout:
    # back off and retry
    pass
except requests.ConnectionError:
    pass

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接