Learning Python Network Programming

(Sean Pound) #1
Chapter 3
location.text = auth.region
data = ET.tostring(XML, encoding='utf-8')
xml_pprint(data)

Here we create an XML tree following the format given in the S3 documentation.
If we run our client now, then we will see the XML shown here:


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


<?xml version="1.0" ?>



eu-west-1

This matches the format specified in the documentation. You can see that we've used
the ns variable to fill the xmlns attribute. This attribute pops up throughout the S3
XML, having the ns variable pre-defined makes it quicker to work with it.


Now, let's add the code to make the request. Replace the xml_pprint(data) at the
end of create_bucket() with the following:


url = 'http://{}.{}'.format(bucket, endpoint)
r = requests.put(url, data=data, auth=auth)
if r.ok:
print('Created bucket {} OK'.format(bucket))
else:
xml_pprint(r.text)

The first line shown here will generate the full URL from our bucket name and
endpoint. The second line will make the request to the S3 API. Notice that we
have used the requests.put() function to make this request using the HTTP PUT
method, rather than by using either the requests.get()method or the requests.
post() method. Also, note that we have supplied our auth object to the call. This
will allow Requests to handle all the S3 authentication for us!


If all goes well , then we print out a message. In case everything does not go as
expected, we print out the response body. S3 returns error messages as XML in the
response body. So we use our xml_pprint() function to display it. We'll look at
working with these errors in the Handling errors section, later on.

Free download pdf