Does requests.codes.ok include a 304?

stett picture stett · Mar 19, 2014 · Viewed 38.8k times · Source

I have a program which uses the requests module to send a get request which (correctly) responds with a 304 "Not Modified". After making the request, I check to make sure response.status_code == requests.codes.ok, but this check fails. Does requests not consider a 304 as "ok"?

Answer

darkheir picture darkheir · Jan 23, 2017

There is a property called ok in the Response object that returns True if the status code is not a 4xx or a 5xx.

So you could do the following:

if response.ok:
    # 304 is included

The code of this property is pretty simple:

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