Managing exceptions with requests

Errors in requests are handled differently from other modules. The following example generates a 404 error indicating that it cannot find the requested resource:

>>> response = requests.get('http://www.google.com/pagenotexists')
>>> response.status_code
404

In this case, the requests module returns a 404 error. To see the exception generated internally, we can use the raise_for_status () method:

>>> response.raise_for_status()
requests.exceptions.HTTPError: 404 Client Error

In the event of making a request to a host that does not exist, and once the timeout has been produced, we get a ConnectionError exception:

>>> r = requests.get('http://url_not_exists')
requests.exceptions.ConnectionError: HTTPConnectionPool(...

In this screen capture, we can see the execution of the previous commands in Python idle:

The request library makes it easier to use HTTP requests in Python compared to urllib. Unless you have a requirement to use urllib, I would always recommend using Requests for your projects in Python.

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

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