为什么我从 Python 请求模块收到超时错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28377421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why do I receive a timeout error from Pythons requests module?
提问by nuttynibbles
I use requests.post(url, headers, timeout=10)
and sometimes I received a ReadTimeout exception HTTPSConnectionPool(host='domain.com', port=443): Read timed out. (read timeout=10)
我使用requests.post(url, headers, timeout=10)
,有时我收到一个ReadTimeout exception HTTPSConnectionPool(host='domain.com', port=443): Read timed out. (read timeout=10)
Since I already set timeout as 10 seconds, why am I still receiving a ReadTimeout exception?
既然我已经将超时设置为 10 秒,为什么我仍然收到 ReadTimeout 异常?
采纳答案by Foon
Per http://docs.python-requests.org/en/latest/user/quickstart/#timeouts, that is the expected behavior. As royhowie mentioned, wrap it in a try/except block (e.g.:
根据http://docs.python-requests.org/en/latest/user/quickstart/#timeouts,这是预期的行为。正如 royhowie 提到的,将它包装在一个 try/except 块中(例如:
try:
requests.post(url, headers, timeout=10)
except requests.exceptions.Timeout:
print "Timeout occurred"
)
)
回答by GLHF
try:
#defined request goes here
except requests.exceptions.ReadTimeout:
# Set up for a retry, or continue in a retry loop
You can wrap it like an exception block like this. Since you asked for this only ReadTimeout
. Otherwise catch all of them;
您可以像这样将其包装成异常块。既然你只要求这个ReadTimeout
。否则全部捕获;
try:
#defined request goes here
except:
# Set up for a retry, or continue in a retry loop
回答by Attrey
Another thing you can try is at the end of your code block, include the following:
您可以尝试的另一件事是在代码块的末尾,包括以下内容:
time.sleep(2)
This worked for me. The delay is longer (in seconds) but might help overcome the issue you're having.
这对我有用。延迟更长(以秒为单位),但可能有助于克服您遇到的问题。