Listing buckets

To list buckets, we need to do a get request with the AWS authentication data. Then we get the response in XML format and get the response.text content:

>>> endpoint = 's3.eu-west-2.amazonaws.com'
>>> auth = aws4auth.AWS4Auth(access_id, access_key, region, 's3')
>>> response = requests.get("http://"+endpoint, auth=auth)
>>> print(response.text)<ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Owner><ID>e6c7c8b59da100190ebe74cf53f402506382c4c2889d64c426f8cfa8026e2f29</ID></Owner><Buckets><Bucket><Name>bucket-aux</Name><CreationDate>2018-12-11T18:33:03.000Z</CreationDate></Bucket><Bucket><Name>zappa-0esu8ehc9</Name><CreationDate>2018-07-23T11:19:50.000Z</CreationDate></Bucket></Buckets></ListAllMyBucketsResult>

Now we can process our XML and convert it into an ElementTree tree:

>>> import xml.etree.ElementTree as ET
>>> root = ET.fromstring(r.text)

We now have an ElementTree instance in the root variable and we can extract such information from XML easily way.

The simplest way of navigating the tree is by using the elements as iterators. Iterating over the root returns each of its child elements, and then we print out the tag of an element by using the tag attribute:

>>> for element in root:
>>> print('Tag: ' + element.tag)

You can find the following code in the s3_list_buckets.py file. This is the function we can use to list buckets to a specific AWS account:

def list_buckets():
print(endpoint)
response = requests.get("http://"+endpoint, auth=auth)
print(response.text)
xml_pprint(response.text)
if response.ok:
root = ET.fromstring(response.text)
for element in root:
print('Tag: ' + element.tag)

In this screenshot, we can see the output of the previous script execution:

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

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