我正在使用requests.adapters.HTTPAdapter
重试我的python3脚本中的请求。而且我发现,当请求超时时,它将抛出ConnectionError
而不是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
。
那么谁能告诉我为什么?
答案 0 :(得分:0)
请求3中的“端口= 88”是否正确?所有其他端口都是port = 80。
# request3
try:
s.get('http://github.com:88', timeout=1)
except requests.ConnectTimeout as e:
print('request3', e)
我对该URL进行了“详细”卷曲,但超时。
curl --url“ http://github.com:88” --verbose
将URL重建为:http://github.com:88/
尝试140.82.113.3 ...
设置了TCP_NODELAY
连接到140.82.113.3端口88失败:超时
无法连接到github.com端口88:超时
关闭连接0
卷曲:(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)
GET / HTTP / 1.1
主持人:github.com
User-Agent:curl / 7.55.1
接受: /
>
<内容长度:0 << / p>
用于托管github.com的连接#0完好无损