Learning Python Network Programming

(Sean Pound) #1
Chapter 2

Handling errors with Requests


Errors in Requests are handled slightly differently from how they are handled with
urllib. Let's work through some error conditions and see how it works. Generate a
404 error by doing the following:





response = requests.get('http://www.google.com/notawebpage')








response.status_code





404


In this situation, urllib would have raised an exception, but notice that Requests
doesn't. The Requests library can check the status code and raise a corresponding
exception, but we have to ask it to do so:





response.raise_for_status()





...


requests.exceptions.HTTPError: 404 Client Error


Now, try it on a successful request:





r = requests.get('http://www.google.com')








r.status_code





200





r.raise_for_status()





None


It doesn't do anything, which in most situations would let our program exit a try/
except block and then continue as we would want it to.


What happens if we get an error that is lower in the protocol stack? Try the following:





r = requests.get('http://192.0.2.1')





...


requests.exceptions.ConnectionError: HTTPConnectionPool(...


We have made a request for a host that doesn't exist and once it has timed out,
we get a ConnectionError exception.


The Requests library simply reduces the workload that is involved in using HTTP
in Python as compared to urllib. Unless you have a requirement for using urllib,
I would always recommend using Requests for your projects.

Free download pdf