Parsing XML and handling errors

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_list_buckets.py, if we replace the access secret with an empty string, then it will produce an error.

This is the function we can use for handling errors:

def handle_error(response):
output = 'Status code: {} '.format(response.status_code)
root = ET.fromstring(response.text)
code = root.find('Code').text
output += 'Error code: {} '.format(code)
message = root.find('Message').text
output += 'Message: {} '.format(message)
print(output)

In you try to execute the s3_list_buckets.py with an empty string in the access secret, it will tell you that it can't authenticate the request because you have set a blank access secret.

In this screenshot, we can see the XML error related to AuthorizationHeaderMalformed:

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

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