【问题标题】:Does requests.codes.ok include a 304?requests.codes.ok 是否包含 304?
【发布时间】:2014-04-25 01:04:17
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    如果状态码不是4xx5xx,则Response 对象中有一个名为ok 的属性会返回True

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

    if response.ok:
        # 304 is included
    

    这个属性的代码很简单:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2010-12-07
        • 2021-08-16
        • 2013-10-16
        • 2018-02-23
        • 2020-03-23
        • 2010-09-19
        • 2012-05-08
        • 2013-02-03
        • 1970-01-01
        相关资源
        最近更新 更多