如何确定request.get是否超时?

时间:2020-02-05 14:51:19

标签: python python-3.x

在这一行代码中:

request = requests.get(url, verify=False, headers=headers, proxies=proxy, timeout=15)

我怎么知道timeout=15已被触发,所以我可以发送一条消息,通知url在15秒内没有发送任何数据?

2 个答案:

答案 0 :(得分:2)

如果在给定时间内根本没有从服务器收到响应,则根据Exa's link,从另一个答案中抛出异常requests.exceptions.Timeout

要测试是否发生这种情况,我们可以使用try, except块来检测它并采取相应的措施,而不仅仅是让程序崩溃。

扩展文档中使用的演示:

import requests

try:
    requests.get('https://github.com/', timeout=0.001)
except requests.exceptions.Timeout as e:
    # code to run if we didn't get a reply
    print("Request timed out!\nDetails:", e)
else:
    # code to run if we did get a response, and only if we did.
    print(r.headers)

仅在适当的地方替换您的网址和超时。

答案 1 :(得分:1)

将引发异常。有关更多信息,请参见this