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

2024-05-16 21:05:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我正在使用请求库来访问HTTP端点。 我想检查一下回复是否成功。

我现在正在做:

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

与其对200到299之间的值进行丑陋的检查,我是否可以使用速记法?


Tags: httpurlgetifhereresponsestatuscode
3条回答

pythonic检查请求成功的方法是有选择地引发异常

try:
    resp = requests.get(url)
    resp.raise_for_status()
except requests.exceptions.HTTPError as err:
    print(err)

EAFP:请求原谅比请求许可更容易:你应该只做你期望的工作,如果操作可能抛出异常,那么捕获它并处理这个事实。

The response has an ^{} property。用这个。

@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

我是个Python新手,但我认为最简单的方法是:

if response.ok:
    # whatever

相关问题 更多 >