gpt4 book ai didi

python - 请求——如何判断您是否收到了成功消息?

转载 作者:太空狗 更新时间:2023-10-29 17:42:09 26 4
gpt4 key购买 nike

我的问题与this one密切相关.

我正在使用 Requests 库访问 HTTP 端点。我想检查响应是否成功。

我目前正在这样做:

r = requests.get(url)
if 200 <= response.status_code <= 299:
# Do something here!

除了对 200 到 299 之间的值进行那种丑陋的检查之外,有没有我可以使用的速记?

最佳答案

The response has an ok property .使用那个:

if response.ok:
...

实现只是围绕 Response.raise_for_status 的尝试/异常(exception),它本身会检查状态代码。

@property
def ok(self):
"""Returns True if :attr:`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``.
"""
try:
self.raise_for_status()
except HTTPError:
return False
return True

关于python - 请求——如何判断您是否收到了成功消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47144606/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com