为什么我会收到来自 Python 请求模块的超时错误?
Why do I receive a timeout error from Pythons requests module?
我使用 requests.post(url, headers, timeout=10)
,有时我会收到 ReadTimeout exception HTTPSConnectionPool(host='domain.com', port=443): Read timed out. (read timeout=10)
既然我已经将超时设置为 10 秒,为什么我仍然收到 ReadTimeout 异常?
Per https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts,这是预期的行为。正如 royhowie 提到的那样,将其包装在 try/except 块中
(例如:
try:
requests.post(url, headers, timeout=10)
except requests.exceptions.Timeout:
print "Timeout occurred"
)
try:
#defined request goes here
except requests.exceptions.ReadTimeout:
# Set up for a retry, or continue in a retry loop
你可以像这样把它包装成异常块。由于您只要求 ReadTimeout
。否则全部抓住;
try:
#defined request goes here
except:
# Set up for a retry, or continue in a retry loop
您可以尝试的另一件事是在代码块的末尾,包括以下内容:
time.sleep(2)
这对我有用。延迟时间较长(以秒为单位),但可能有助于解决您遇到的问题。
我使用 requests.post(url, headers, timeout=10)
,有时我会收到 ReadTimeout exception HTTPSConnectionPool(host='domain.com', port=443): Read timed out. (read timeout=10)
既然我已经将超时设置为 10 秒,为什么我仍然收到 ReadTimeout 异常?
Per https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts,这是预期的行为。正如 royhowie 提到的那样,将其包装在 try/except 块中 (例如:
try:
requests.post(url, headers, timeout=10)
except requests.exceptions.Timeout:
print "Timeout occurred"
)
try:
#defined request goes here
except requests.exceptions.ReadTimeout:
# Set up for a retry, or continue in a retry loop
你可以像这样把它包装成异常块。由于您只要求 ReadTimeout
。否则全部抓住;
try:
#defined request goes here
except:
# Set up for a retry, or continue in a retry loop
您可以尝试的另一件事是在代码块的末尾,包括以下内容:
time.sleep(2)
这对我有用。延迟时间较长(以秒为单位),但可能有助于解决您遇到的问题。