python requests: how to check for “200 OK”

前端 未结 7 1028
清歌不尽
清歌不尽 2020-12-31 00:57

What is the easiest way to check whether the response received from a requests post was \"200 OK\" or an error has occurred?

I tried doing something like this:

7条回答
  •  说谎
    说谎 (楼主)
    2020-12-31 01:40

    According to the docs, there's a status_code property on the response-object. So you can do the following:

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

    EDIT:

    As others have pointed out, a simpler check would be

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

    if you want to consider all 2xx response codes and not 200 explicitly. You may also want to check Peter's answer for a more python-like way to do this.

提交回复
热议问题