Skip to main content
 首页 » 编程设计

python之为什么请求响应对象 __bool__ 检查 200 = status 400

2025年05月04日11zdz8207

根据source of the Requests module ,__bool__ 函数仅用于检查响应的状态代码是否在 200 到 400 之间。

Returns True if :attr:`status_code` is less than 400. 
This attribute checks if the status code of the response is between 
400 and 600 to see if there was a client error or a server error. If 
the status code, is between 200 and 400, this will return True. This 
is **not** a check to see if the response code is ``200 OK``. 

__bool__ 函数的使用导致以下代码无法按预期工作:

def request_url(url): 
    error_message = None 
    try: 
        r = requests.get(url) 
    except: 
        # Do some other error handling... 
        error_message = "Bad request." 
        r = None 
    return r, error_message 
 
r, error_message = request_url(url) 
if r: 
    # Do some stuff to the response 
    operate_on_response(r) 
else: 
    # Skip this response object and move to the next. 

当我请求的 url 的状态代码是 500 时,语句 if r: 返回 False。即使未触发异常,if r: 返回 False 每次出现服务器错误。不过,我的目的是测试响应对象是否存在。

我不是在寻求解决方法:我知道我可以检查 error_message 是否不是 None。上面的代码只是一个例子,不是我正在使用的实际代码。

但是,对我来说,使用 __bool__ 函数来检查状态代码是否介于两个值之间似乎并不自然或合乎逻辑。就像我说的,我可以自己找到解决方法,但我主要是想问为什么?为什么要这样使用 __bool__ 方法?有没有我没看到的逻辑?

请您参考如下方法:

如果请求成功,该方法返回True。 2xx 和 3xx 范围内的状态码均表示响应正确且成功,而其他状态码均表示错误。

在幕后,__bool__ 方法本质上是 response.ok attribute 的别名。 :

Returns True if status_code is less than 400, False if not.

This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code is between 200 and 400, this will return True. This is not a check to see if the response code is 200 OK.

这与 response.raise_for_status() method 相呼应,当存在“错误”状态代码时,将引发 HTTPError 异常。

requests API 中任何可以返回Response 实例的函数或方法,总是这样做,否则会引发异常。您永远无法从 API 获得 None 或其他 false-y 值,因此没有其他用于测试 bool 值的用例。因此,响应的 bool 值可以被重载以表示任何,在这里它被用来方便地测试响应的“okayness”:

response = requests.get(...) 
if response: 
    # success! yay, do something meaningful with the response data 

这比为相反的状态引发异常更适合某些用例,在相反的状态下您从服务器获得错误状态。