我正在尝试分析未启动测试服务器时Requests返回的错误。
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
类的构建方式到底如何?
答案 0 :(得分:0)
TL; DR 您不能。
至少不太好。
好处是您不应该,或者至少不需要。
考虑:
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