Requests — how to tell if you're getting a success message? Requests — how to tell if you're getting a success message? python python

Requests — how to tell if you're getting a success message?


The response has an ok property. Use that:

if response.ok:    ...

The implementation is just a try/except around Response.raise_for_status, which is itself checks the status code.

@propertydef ok(self):    """Returns True if :attr:`status_code` is less than 400, False if not.    This attribute checks if the status code of the response is between    400 and 600 to see if there was a client error or a server error. If    the status code is between 200 and 400, this will return True. This    is **not** a check to see if the response code is ``200 OK``.    """    try:        self.raise_for_status()    except HTTPError:        return False    return True


I am a Python newbie but I think the easiest way is:

if response.ok:    # whatever


The pythonic way to check for requests success would be to optionally raise an exception with

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.