我试图解析测试服务器未启动时请求返回的错误。
print("%s\n" % type(error))
<class 'requests.exceptions.ConnectionError'>
print("%s\n" % error)
HTTPConnectionPool(host='localhost', port=8080): Max retries exceeded with url: /test_soap (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fecf0892a90>: Failed to establish a new connection: [Errno 111] Connexion refusée'))
打开/usr/lib/python3.7/site-packages/requests/exceptions.py
时,可以看到ConnectionError
类具有response
和request
属性:
print("%s\n" % error.response)
None
print("%s\n" % error.request)
<PreparedRequest [POST]>
但是我想访问urllib3.connection.HTTPConnection
对象,以便打印Failed to establish a new connection
错误消息。
requests.exceptions.ConnectionError
类是如何生成的,以便在打印它时显示此错误消息?
发布于 2018-11-13 11:42:28
TL;博士你不能。
至少不是很好。
好的是你不应该,或者至少你不需要。
考虑:
import requests
try:
requests.get('http://localhost')
except Exception as error:
print(error)
print(type(error))
print([o for o in dir(error) if not o.startswith('__')])
输出
# HTTPConnectionPool(host='localhost', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000019F34649C18>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))
# <class 'requests.exceptions.ConnectionError'>
# ['args', 'characters_written', 'errno', 'filename',
# 'filename2', 'request', 'response',
# 'strerror', 'winerror', 'with_traceback']
如果我们查看最后一个输出,除了args
之外,没有什么东西真正突出。
print(error.args)
与往常一样,这将是一个包含抛出对象的元组:
# (MaxRetryError("HTTPConnectionPool(host='localhost', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x00000189C4D7AD30>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))"),)
从这里到底层的urlib3
异常是丑陋和混乱的,并没有真正给我们任何我们还不知道的新信息:
print(error.args[0].reason.args[0])
# <urllib3.connection.HTTPConnection object at 0x0000023476C40390>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it
https://stackoverflow.com/questions/53280054
复制相似问题