python中响应对象的真实性

时间:2015-10-25 11:06:52

标签: python exception-handling response

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

我想使用以下代码

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

但它始终显示""作为400的响应,视为错误

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

为什么会这样

2 个答案:

答案 0 :(得分:3)

Response object&#39; __bool__会返回对象的ok属性,对于任何响应4xx或5xx,该属性又为False。< / p>

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

中所述

答案 1 :(得分:0)

要在上面的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)