我有一个程序,它使用请求模块发送一个get请求,它正确地响应304“Not Modified”。发出请求后,我会检查以确保response.status_code == requests.codes.ok
,但此检查失败。请求不将304视为“ok”吗?
答案 0 :(得分:17)
您可以查看实际代码in the source。 ok
仅表示200。
答案 1 :(得分:14)
Response
对象中有一个名为ok
的属性,如果状态代码不是True
或4xx
,则返回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)
总之,您可以访问任何请求 - 响应,如演示。我相信有更好的方法,但这对我有用。