Learning Python Network Programming

(Sean Pound) #1

APIs in Action


Parsing XML and handling errors


If you ran into any errors while running the aforementioned code, then you'll notice
that a clear error message will not get displayed. S3 embeds error messages in the
XML returned in the response body, and until now we've just been dumping the raw
XML to the screen. We can improve on this and pull the text out of the XML. First,
let's generate an error message so that we can see what the XML looks like. In
s3_client.py, replace your access secret with an empty string, as shown here:


access_secret = ''

Now, try and perform the following operation on the service:


$ python3.4 s3_client.py create_bucket failbucket.example.com


<?xml version="1.0" ?>



SignatureDoesNotMatch


The request signature we calculated does not match the
signature you provided. Check your key and signing
method.

AKIAJY5II3SZNHZ25SUA
AWS4-HMAC-SHA256...
e43e2130...
41 57 53 34...
PUT...
50 55 54...
86F25A39912FC628
kYIZnLclzIW6CmsGA....

The preceding XML is the S3 error information. I've truncated several of the fields
so as to show it here. Your code block will be slightly longer than this. In this case,
it's telling us that it can't authenticate our request, and this is because we have set a
blank access secret.


Parsing XML


Printing all of the XML is too much for an error message. There's a lot of extraneous
information which isn't useful to us. It would be better if we could just pull out the
useful parts of the error message and display them.


Well, ElementTree gives us some powerful tools for extracting such information
from XML. We're going back to XML for a while to explore these tools a little.

Free download pdf