作者:caoxingchi_411 | 来源:互联网 | 2023-01-09 22:50
我的问题与这个问题密切相关.
我正在使用Requests库来命中HTTP端点.我想检查一下响应是否成功.
我目前正在这样做:
r = requests.get(url)
if 200 <= response.status_code <= 299:
# Do something here!
而不是对200到299之间的值进行那种丑陋的检查,我可以用一个简写吗?
1> wim..:
该回复有一个ok
属性.用那个.
@property
def ok(self):
"""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``.
"""
try:
self.raise_for_status()
except HTTPError:
return False
return True