- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
根据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
ifstatus_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
这比为相反的状态引发异常更适合某些用例,在相反的状态下您从服务器获得错误状态。
关于python - 为什么请求响应对象 __bool__ 检查 200 <= status < 400?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48347290/
我定义了一个类,其中它的 __ge__方法返回自身的一个实例,其 __bool__不允许调用方法(类似于 Pandas Series)。 为什么是 X.__bool__在 np.int8(0) .__
这个问题在这里已经有了答案: 关闭10年前。 Possible Duplicate: defining “boolness” of a class in python 我以为这应该打印“False”,
我正在尝试使用 dask API 为我的特定应用程序运行 DAG 任务。举一个人为的示例,我希望任务传递其成功/失败标志并将其用作其他任务的输入。 但是,dask 不让我这样做 __bool__对延迟
根据source of the Requests module ,__bool__ 函数仅用于检查响应的状态代码是否在 200 到 400 之间。 Returns True if :attr:`sta
作为单元测试的一部分,我正在使用出色的 Requests 库测试一些响应。您可以使用此库做一些很酷的事情,即测试对 200 的响应。通过简单地调用 OK 状态代码: r = requests.get(
我是一名优秀的程序员,十分优秀!