请求.codes.ok是否包含304?

时间:2014-03-19 02:00:31

标签: python python-requests http-status-code-304

我有一个程序,它使用请求模块发送一个get请求,它正确地响应304“Not Modified”。发出请求后,我会检查以确保response.status_code == requests.codes.ok,但此检查失败。请求不将304视为“ok”吗?

3 个答案:

答案 0 :(得分:17)

您可以查看实际代码in the sourceok仅表示200。

答案 1 :(得分:14)

Response对象中有一个名为ok的属性,如果状态代码不是True4xx,则返回5xx

所以你可以做到以下几点:

if response.ok:
    # 304 is included

此属性的代码非常简单:

@property
def ok(self):
    try:
        self.raise_for_status()
    except HTTPError:
        return False
    return True

答案 2 :(得分:2)

您可以在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)

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

相关问题