【问题标题】:python requests: how to check for "200 OK"python请求:如何检查“200 OK”
【发布时间】:2019-01-08 07:47:28
【问题描述】:

检查从请求帖子收到的响应是“200 OK”还是发生错误的最简单方法是什么?

我试着做这样的事情:

....
resp = requests.post(my_endpoint_var, headers=header_var, data=post_data_var)
print(resp)
if resp == "<Response [200]>":
    print ('OK!')
else:
    print ('Boo!')

屏幕上的输出是:

Response [200] (including the "<" and ">")
Boo!

所以即使我得到 200,我在 if 语句中的检查也不匹配?

【问题讨论】:

  • 我不确定它是否有效,但尝试将 print(resp) 替换为 print(resp.status_code) 并检查它是否有效
  • 我认为 resp 应该有一个字段“status_code”。检查 resp.status_code == 200

标签: python python-requests


【解决方案1】:

根据docs,响应对象上有一个status_code 属性。因此,您可以执行以下操作:

if resp.status_code == 200:
    print ('OK!')
else:
    print ('Boo!')

编辑:

正如其他人指出的那样,更简单的检查是

if resp.ok:
    print ('OK!')
else:
    print ('Boo!')

如果您想明确考虑所有2xx 响应代码而不是200。 您可能还想查看 Peter 的 answer 以获得更类似于 python 的方式来执行此操作。

【讨论】:

  • 值得一提的是,虽然resp 对象打印为 &lt;Response [200]&gt;,但这并不意味着它与该字符串相同。
【解决方案2】:

只需检查响应属性resp.ok。对于所有 2xx 响应,它是 True,但对于 4xx 和 5xx,它是 False。但是,pythonic 检查成功的方法是选择性地使用Response.raise_for_status() 引发异常:

try:
    resp = requests.get(url)
    resp.raise_for_status()
except requests.exceptions.HTTPError as err:
    print(err)

EAFP:EA要求F宽恕比P更容易:你应该这样做您期望工作的内容,如果操作可能引发异常,则捕获它并处理该事实。

【讨论】:

  • 虽然 EAFP 适用于 大多数 Python,但我认为在这种情况下最好先请求响应。例如,如果您正在处理 API,它可能会给出 4xx 响应而不会引发任何异常。
  • 就是这样!
【解决方案3】:

我很惊讶没有人提到这一点:

如果您想检查正好是 200 响应

if resp.status_code == requests.codes.ok:

status_code of a response 包含返回的 HTTP 状态。

requests.codes.ok 正好是 200。


如果要检查状态码是否为“ok”,并且不是错误

if resp.ok:

ok attribute of a response 检查响应的status code 是否小于 400。


确保您知道要检查的是什么,例如 201 HTTP Created 是一个成功的响应,如果您只检查 正好 200,您将忽略它。

【讨论】:

    【解决方案4】:

    由于在 HTTP 中任何 2XX 类响应都被视为 successful,因此我会使用:

    # changed the direction of the less than sign
    if 200 <= resp.status_code >= 299:
        print ('OK!') 
    else:
        print ('Boo!')
    

    【讨论】:

    • if resp.ok 效果一样。
    • 我不会说同样的效果,因为它包括 3xx
    【解决方案5】:

    检查会更简单

        if resp.ok :
            print ('OK!')
        else:
            print ('Boo!')
    

    【讨论】:

    • 这不只检查 200 OK。
    【解决方案6】:

    尝试:

    if resp.status_code == 200:
        print ('OK!')
    else:
        print ('Boo!)
    

    【讨论】:

      【解决方案7】:

      resp.status_code 会以整数形式返回状态码。

      http://docs.python-requests.org/en/master/

      【讨论】:

        【解决方案8】:

        在简单的情况下:

        import requests
        
        response = requests.get(url)
        if not response:
            #handle error here
        else:
            #handle normal response
        

        【讨论】:

          猜你喜欢
          • 2019-07-08
          • 2013-01-10
          • 2011-03-28
          • 2012-12-22
          • 2014-05-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-04
          相关资源
          最近更新 更多