26

我有一个程序,它使用请求模块发送一个获取请求,该请求(正确)以 304“未修改”响应。提出请求后,我检查以确保response.status_code == requests.codes.ok,但此检查失败。请求是否不将 304 视为“ok”?

4

3 回答 3

45

如果状态码不是 a或 a ,则返回okResponse对象中有一个属性。True4xx5xx

因此,您可以执行以下操作:

if response.ok:
    # 304 is included

这个属性的代码非常简单:

@property
def ok(self):
    try:
        self.raise_for_status()
    except HTTPError:
        return False
    return True
于 2017-01-23T14:31:44.893 回答
27

您可以检查源代码中的实际代码。ok仅表示 200。

于 2014-03-19T02:06:01.320 回答
4

您可以在source code中查看 requests.status 代码的实现。
该实现允许您访问所有/任何类型的status_codes,如下所示:

import requests
import traceback
url = "https://google.com"
req = requests.get(url)
try:
    if req.status_code == requests.codes['ok']: # Check the source code for all the codes
        print('200')
    elif req.status_code == requests.codes['not_modified']: # 304
        print("304")
    elifreq.status_code == requests.codes['not_found']: # 404
        print("404")
    else:
        print("None of the codes")
except:
    traceback.print_exc(file=sys.stdout)

总之,您可以像演示的那样访问任何请求-响应。我相信有更好的方法,但这对我有用。

于 2018-03-12T12:46:13.623 回答