首页 > 解决方案 > 为什么请求在 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.

那么谁能告诉我为什么?

标签: pythonpython-requests

解决方案


请求 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 保持不变


推荐阅读