Book Image

Learning Python Network Programming

By : Dr. M. O. Faruque Sarker, Samuel B Washington, Sam Washington
Book Image

Learning Python Network Programming

By: Dr. M. O. Faruque Sarker, Samuel B Washington, Sam Washington

Overview of this book

Table of Contents (17 chapters)
Learning Python Network Programming
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Handling problems


Status codes help us to see whether our response was successful or not. Any code in the 200 range indicates a success, whereas any code in either the 400 range or the 500 range indicates failure.

Status codes should always be checked so that our program can respond appropriately if something goes wrong. The urllib package helps us in checking the status codes by raising an exception if it encounters a problem.

Let's go through how to catch these and handle them usefully. For this try the following command block:

>>> import urllib.error
>>> from urllib.request import urlopen
>>> try:
...   urlopen('http://www.ietf.org/rfc/rfc0.txt')
... except urllib.error.HTTPError as e:
...   print('status', e.code)
...   print('reason', e.reason)
...   print('url', e.url)
...
status: 404
reason: Not Found
url: http://www.ietf.org/rfc/rfc0.txt

Here we've requested RFC 0, which doesn't exist. So the server has returned a 404 status code, and urllib has spotted this...