【发布时间】:2014-04-25 01:04:17
【问题描述】:
我有一个程序,它使用请求模块发送一个获取请求,该请求(正确)响应 304“未修改”。发出请求后,我检查以确保response.status_code == requests.codes.ok,但此检查失败。请求不会将 304 视为“ok”吗?
【问题讨论】:
标签: python python-requests http-status-code-304
我有一个程序,它使用请求模块发送一个获取请求,该请求(正确)响应 304“未修改”。发出请求后,我检查以确保response.status_code == requests.codes.ok,但此检查失败。请求不会将 304 视为“ok”吗?
【问题讨论】:
标签: python python-requests http-status-code-304
如果状态码不是4xx 或5xx,则Response 对象中有一个名为ok 的属性会返回True。
因此您可以执行以下操作:
if response.ok:
# 304 is included
这个属性的代码很简单:
@property
def ok(self):
try:
self.raise_for_status()
except HTTPError:
return False
return True
【讨论】:
您可以查看实际代码in the source。 ok 仅表示 200 个。
【讨论】:
requests.codes.ok 与 requests.models.Response.ok 不同。您是正确的,requests.models.Response.ok 确实对于 200 requests.codes.ok 只是值 200。您可以使用 import requests; print(requests.codes.ok) 自己查看
您可以在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)
总之,您可以像演示的那样访问任何请求-响应。我确信有更好的方法,但这对我有用。
【讨论】: