首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >解析对象内容

解析对象内容
EN

Stack Overflow用户
提问于 2018-11-13 11:28:45
回答 1查看 813关注 0票数 0

我试图解析测试服务器未启动时请求返回的错误。

代码语言:javascript
代码运行次数:0
运行
复制
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类具有responserequest属性:

代码语言:javascript
代码运行次数:0
运行
复制
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类是如何生成的,以便在打印它时显示此错误消息?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-13 11:42:28

TL;博士你不能。

至少不是很好。

好的是你不应该,或者至少你不需要。

考虑:

代码语言:javascript
代码运行次数:0
运行
复制
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('__')])

输出

代码语言:javascript
代码运行次数:0
运行
复制
# 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之外,没有什么东西真正突出。

代码语言:javascript
代码运行次数:0
运行
复制
print(error.args)

与往常一样,这将是一个包含抛出对象的元组:

代码语言:javascript
代码运行次数:0
运行
复制
# (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异常是丑陋和混乱的,并没有真正给我们任何我们还不知道的新信息:

代码语言:javascript
代码运行次数:0
运行
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53280054

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档