Python 请求—;如何判断你是否';你收到了成功的信息吗?

Python 请求—;如何判断你是否';你收到了成功的信息吗?,python,http,python-requests,httprequest,http-response-codes,Python,Http,Python Requests,Httprequest,Http Response Codes,我的问题与此密切相关 我正在使用请求库访问HTTP端点。 我想检查一下回复是否成功 我目前正在这样做: r = requests.get(url) if 200 <= response.status_code <= 299: # Do something here! r=requests.get(url) 如果200。使用以下命令: if response.ok: ... 该实现只是一个try/except-around,它本身检查状态代码 @property d

我的问题与此密切相关

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

我目前正在这样做:

r = requests.get(url)
if 200 <= response.status_code <= 299:
    # Do something here!
r=requests.get(url)
如果200。使用以下命令:

if response.ok:
    ...
该实现只是一个try/except-around,它本身检查状态代码

@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新手,但我认为最简单的方法是:

if response.ok:
    # whatever
检查请求成功的pythonic方法是有选择地使用

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

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

你可以使用
r.raise_for_status()
,但你拥有的并不难看。请注意,这将3xx重定向范围计算为OK,与问题中的代码不同,我认为您通常不会看到300范围的状态,因为
请求将遵循重定向。您将获得重定向到的URL的状态。如果您通过
allow_redirects=False
,它将不会跟随重定向。我认为这也可能是1x响应的问题,它不会引发状态,也不在问题的代码范围内。