python 中响应对象的真实性

Truthness of response objects in python

我正在使用 python 请求库,我收到了 400 个响应。

我想使用下面的代码

data =  response.json() if response else ""

但它总是显示 "" 作为对 400 被视为 false

的响应
(Pdb) self.response
<Response [400]>
(Pdb) assert self.response
*** AssertionError

这是为什么

A Response object__bool__ returns 对象的 ok 属性,对于任何响应 4xx 或 False 5xx.

您仍然可以检查响应的各个字段,如 the documentation 中所述。

要为以上 torek 的回答添加一些细节,仅 400 <= self.status_code < 600 为False,其他为True,您可以在下面看到Response object的相关代码。

def __bool__(self):
    """Returns true if :attr:`status_code` is 'OK'."""
    return self.ok

<snip>

@property
def ok(self):
    try:
        self.raise_for_status()
    except HTTPError:
        return False
    return True

<snip>

def raise_for_status(self):
    """Raises stored :class:`HTTPError`, if one occurred."""

    http_error_msg = ''

    if 400 <= self.status_code < 500:
        http_error_msg = '%s Client Error: %s for url: %s' % (self.status_code, self.reason, self.url)

    elif 500 <= self.status_code < 600:
        http_error_msg = '%s Server Error: %s for url: %s' % (self.status_code, self.reason, self.url)

    if http_error_msg:
        raise HTTPError(http_error_msg, response=self)