jar*_*889 1 python python-requests
根据请求模块的来源,该__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``.
Run Code Online (Sandbox Code Playgroud)
使用该__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.
Run Code Online (Sandbox Code Playgroud)
if r:当我请求的url的状态代码是500时,该语句返回False.即使异常未被触发,每次出现服务器错误时if r:返回False.我的目的是测试响应对象是否存在.
我不是要求解决方法:我知道我可以检查error_message是不是None.上面的代码只是一个例子,而不是我正在使用的实际代码.
但是,对我来说,使用该__bool__函数检查状态代码是否在两个值之间似乎并不自然或合乎逻辑.就像我说的,我自己可以找到一个解决方法,但我主要是问为什么?为什么用__bool__这种方法?我有没有看到一些逻辑?
True如果请求成功,则返回该方法.2xx和3xx范围内的状态代码均表示正确且成功的响应,而其他状态代码均表示错误.
在引擎盖下,该__bool__方法本质上是response.ok属性的别名:
返回
Trueifstatus_code小于400,False否则返回.此属性检查响应的状态代码是否介于400和600之间,以查看是否存在客户端错误或服务器错误.如果状态代码介于200和400之间,则返回
True.这不是检查响应代码是否为200 OK.
这与该response.raise_for_status()方法相呼应,HTTPError当存在"错误"状态代码时,该方法将引发异常.
requestsAPI中可以返回Response实例的任何函数或方法将始终这样做,或引发异常.您无法None从API中获取其他false-y值,因此没有其他用于测试布尔值的用例.因此,响应的布尔值可以重载为任何意义,在这里它用于使测试响应的"好"性变得容易:
response = requests.get(...)
if response:
# success! yay, do something meaningful with the response data
Run Code Online (Sandbox Code Playgroud)
这适用于某些用例,而不是为相反的状态引发异常,从而从服务器获得错误状态.