28

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

stett
  • 1,351
  • 1
  • 11
  • 24

4 Answers4

49

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
Alonme
  • 1,364
  • 15
  • 28
darkheir
  • 8,844
  • 6
  • 45
  • 66
28

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

Dmitry Shevchenko
  • 31,814
  • 10
  • 56
  • 62
  • 10
    Thanks - Ha - I never realized that the '✓' character was also mapped to 200. – stett Mar 19 '14 at 02:10
  • 2
    this answer is FALSE, both according to the documentation [http://docs.python-requests.org/en/master/api/#requests.Response.ok] and according to the source [http://docs.python-requests.org/en/master/_modules/requests/models/#Response.raise_for_status] – Matti Lyra Mar 06 '19 at 16:42
  • 6
    @MattiLyra you're actually incorrect here. `requests.codes.ok` is not the same as `requests.models.Response.ok`. You're correct that `requests.models.Response.ok` does indeed return true for values of 200 <= status_code < 400, but `requests.codes.ok` is just the value 200. You can see for yourself with `import requests; print(requests.codes.ok)` – minhaz1 May 23 '19 at 20:13
4

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.

user 451
  • 462
  • 6
  • 8
0

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

Efraim
  • 43
  • 6