[英]How to know for sure if requests.get has timed out?
In this line of code:在这行代码中:
request = requests.get(url, verify=False, headers=headers, proxies=proxy, timeout=15)
How do I know that timeout=15
has been triggered so I can send a message that url
did not send any data in 15 seconds?我怎么知道timeout=15
已被触发,以便我可以发送url
在 15 秒内未发送任何数据的消息?
If a response is not received from the server at all within the given time, then an exception requests.exceptions.Timeout
is thrown, as per Exa's link from the other answer.如果在给定时间内根本没有从服务器收到响应,则根据Exa来自其他答案的链接,抛出异常requests.exceptions.Timeout
。
To test if this occurred we can use a try, except
block to detect it and act accordingly, rather than just letting our program crash.为了测试这是否发生,我们可以使用try, except
块来检测它并采取相应的行动,而不是让我们的程序崩溃。
Expanding on the demonstration used in the docs:扩展文档中使用的演示:
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)
Just substitute your url and timeout where appropriate.只需在适当的地方替换您的网址和超时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.