Python requests.codes.ok 是否包含 304?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22494794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does requests.codes.ok include a 304?
提问by stett
I have a program which uses the requests module to send a get request which (correctly) responds with a 304 "Not Modified". After making the request, I check to make sure response.status_code == requests.codes.ok, but this check fails. Does requests not consider a 304 as "ok"?
我有一个程序,它使用请求模块发送一个获取请求,该请求(正确)以 304“未修改”响应。提出请求后,我检查以确保response.status_code == requests.codes.ok,但此检查失败。请求不会将 304 视为“确定”吗?
采纳答案by Dmitry Shevchenko
You can check actual codes in the source. okmeans 200 only.
回答by darkheir
There is a property called okin the Responseobject that returns Trueif the status code is not a 4xxor a 5xx.
如果状态代码不是 a或 a ,则ok在Response对象中调用一个属性返回。True4xx5xx
So you could do the following:
因此,您可以执行以下操作:
if response.ok:
# 304 is included
The code of this property is pretty simple:
这个属性的代码非常简单:
@property
def ok(self):
try:
self.raise_for_status()
except HTTPError:
return False
return True
回答by user 451
You can check the implementation of requests.status code here source code.
The implementation allows you to access all/any kind of status_codesas follow:
您可以在源代码中查看 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)
In conclusion, you can access any request-response like demonstrated. I am sure there are better ways but this worked for me.
总之,您可以像演示一样访问任何请求-响应。我相信有更好的方法,但这对我有用。

