python - 为什么请求在 HTTPAdapter 中抛出 ConnectionError 而不是 ReadTimeout?
问题描述
我requests.adapters.HTTPAdapter
用来在我的 python3 脚本中重试请求。我发现当请求超时时,它会抛出 aConnectionError
而不是 a ReadTimeout
。
我正在使用 python3.7.4 和 requests==2.22.0。
requests#2392可能会有所帮助,但我不确定它们是否相同。
import requests
from requests.adapters import HTTPAdapter
# request1
try:
requests.get('http://httpbin.org/delay/2', timeout=1)
except requests.ReadTimeout as e:
print('request1', e)
s = requests.Session()
s.mount('http://', HTTPAdapter(max_retries=1))
# request2
try:
s.get('http://httpbin.org/delay/2', timeout=1)
except requests.ReadTimeout as e:
print('this line will not be printed')
except requests.ConnectionError as e:
print('request2', e)
# request3
try:
s.get('http://github.com:88', timeout=1)
except requests.ConnectTimeout as e:
print('request3', e)
s.close()
这是输出:
request1 HTTPConnectionPool(host='httpbin.org', port=80): Read timed out. (read timeout=1)
request2 HTTPConnectionPool(host='httpbin.org', port=80): Max retries exceeded with url: /delay/2 (Caused by ReadTimeoutError("HTTPConnectionPool(host='httpbin.org', port=80): Read timed out. (read timeout=1)"))
request3 HTTPConnectionPool(host='github.com', port=88): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x10d1a6c10>, 'Connection to github.com timed out. (connect timeout=1)'))
在 request2 中,我希望ReadTimeout
可以捕获异常,而不是ConnectionError
.
那么谁能告诉我为什么?
解决方案
请求 3 中的“端口 = 88”是否正确?所有其他端口= 80。
# request3
try:
s.get('http://github.com:88', timeout=1)
except requests.ConnectTimeout as e:
print('request3', e)
我对该网址做了一个“详细”的卷曲,我得到了一个超时。
curl --url " http://github.com:88 " --verbose
重建网址: http: //github.com :88/
正在尝试 140.82.113.3...
TCP_NODELAY 设置
连接到 140.82.113.3 端口 88 失败:超时
连接github.com 88端口失败:超时
关闭连接 0
curl: (7) 连接github.com 88端口失败:超时
相同的呼叫,但端口 80 很快并且可以连接
curl --url " http://github.com:80 " --verbose
重建 URL 到: http: //github.com :80/
正在尝试 192.30.253.113...
TCP_NODELAY 设置
连接到 github.com (192.30.253.113) 端口 80 (#0)
获取/HTTP/1.1
主办方:github.com
用户代理:curl/7.55.1
接受:/
>
< HTTP/1.1 301 永久移动
< 内容长度:0
< 位置:https ://github.com/
<
与主机 github.com 的连接 #0 保持不变
推荐阅读
- c# - 本地主机上应用程序的自签名证书 - 套接字 TCP (TLS)
- npm - Verdaccio:如何使用正确的凭据从 Github Actions 发布到自定义服务器?
- java - 我可以将整个应用程序放在一个 JAR 文件中吗?
- python - 参数“字符串”的类型不正确(预期为 str,得到列表) Spacy NLP
- c# - 从 PowerShell 提示符运行时初始化数据库问题
- python - 如何处理特定条件并对其进行测试
- html - 表单错误中的“action_page.php”导致错误 404
- python - Dji Tello EDU | 视频群
- python - 从本地网络访问 Flask 应用程序
- javascript - Firestore - 根据名称中带有句点 (.) 的键读取