Looking up built-in response status codes

Status codes are helpful in letting us know the result, once a request is sent. To know about this, we can use status_code:

>>> r = requests.get('http://google.com')
>>> r.status_code
200

To make it much easier to deal with status_codes, Requests has got a built-in status code lookup object which serves as an easy reference. We must compare the requests.codes.ok with r.status_code to achieve this. If the result turns out to be True, then it's 200 status code, and if it's False, it's not. We can also compare the r.status.code with requests.codes.ok, requests.code.all_good to get the lookup work.

>>> r = requests.get('http://google.com')
>>> r.status_code == requests.codes.ok
True

Now, let's try checking with a URL that is non-existent.

>>> r = requests.get('http://google.com/404')
>>> r.status_code == requests.codes.ok
False

We have got the facility to deal with the bad requests like 4XX and 5XX type of errors, by notifying with the error codes. This can be accomplished by using Response.raise_for_status().

Let us try this by sending a bad request first:

>>> bad_request = requests.get('http://google.com/404')
>>> bad_request.status_code
404
>>>bad_request.raise_for_status()
---------------------------------------------------------------------------
HTTPError                              Traceback (most recent call last)
----> bad_request..raise_for_status()

File "requests/models.py",  in raise_for_status(self)
   771
   772         if http_error_msg:
--> 773             raise HTTPError(http_error_msg, response=self)
   774
   775     def close(self):

HTTPError: 404 Client Error: Not Found

Now if we try a working URL, we get nothing in response, which is a sign of success:

>>> bad_request = requests.get('http://google.com')
>>> bad_request.status_code
200
>>> bad_request.raise_for_status()
>>>

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.186.143