Question

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"?

Was it helpful?

Solution 2

You can check actual codes in the source. ok means 200 only.

OTHER TIPS

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

You can check the implementation of requests.status code here source code.
The implementation allows you to access all/any kind of status_codes as follow:

import requests
import traceback
url = "https://google.com"
req = requests.get(url)
try:
    if req.status_code == requests.codes['ok']: # Check the source code for all the codes
        print('200')
    elif req.status_code == requests.codes['not_modified']: # 304
        print("304")
    elifreq.status_code == requests.codes['not_found']: # 404
        print("404")
    else:
        print("None of the codes")
except:
    traceback.print_exc(file=sys.stdout)

In conclusion, you can access any request-response like demonstrated. I am sure there are better ways but this worked for me.

.ok "..If the status code is between 200 and 400, this will return True."

mentioned in source code as:

"""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. """

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top