分析对象内容

2024-06-23 19:49:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试分析测试服务器未启动时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和{}属性:

^{pr2}$

{{cd6>无法访问{cd6>消息。在

当我打印这个错误消息时,requests.exceptions.ConnectionError类是如何生成的?在


Tags: 服务器消息type错误errorconnectionrequestsclass
1条回答
网友
1楼 · 发布于 2024-06-23 19:49:12

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('__')])

输出

^{pr2}$

如果我们看一下最后一个输出,除了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

相关问题 更多 >

    热门问题