python requests: how to check for “200 OK”

前端 未结 7 1024
清歌不尽
清歌不尽 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:33

    In easy case:

    import requests
    
    response = requests.get(url)
    if not response:
        #handle error here
    else:
        #handle normal response
    
    0 讨论(0)
  • 2020-12-31 01:36

    resp.status_code will return the status code as an integer.

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-31 01:40

    Just check the response attribute resp.ok. It is True for all 2xx responses, but False for 4xx and 5xx. However, the pythonic way to check for success would be to optionally raise an exception with Response.raise_for_status():

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

    EAFP: It’s Easier to Ask for Forgiveness than Permission: You should just do what you expect to work and if an exception might be thrown from the operation then catch it and deal with that fact.

    0 讨论(0)
  • 2020-12-31 01:40

    Much simpler check would be

        if resp.ok :
            print ('OK!')
        else:
            print ('Boo!')
    
    0 讨论(0)
  • 2020-12-31 01:44

    try:

    if resp.status_code == 200:
        print ('OK!')
    else:
        print ('Boo!)
    
    0 讨论(0)
提交回复
热议问题