Learning Python Network Programming

(Sean Pound) #1

APIs in Action


This creates the bucket in the default standard US region. We can supply a different
region, as shown here:





from boto.s3.connection import Location








conn.create_bucket('mybucket.example.com', location=Location.EU)





The region names we need to use for this function are different to the ones we used
when creating buckets earlier. To see a list of acceptable region names do this:





[x for x in dir(Location) if x.isalnum()]





['APNortheast', 'APSoutheast', 'APSoutheast2', 'CNNorth1', 'DEFAULT',
'EU', 'SAEast', 'USWest', 'USWest2']


Do the following to display a list of the buckets we own:





buckets = conn.get_all_buckets()








[b.name for b in buckets]





['mybucket.example.com', 'mybucket2.example.com']


We can also list the contents of a bucket. To do so, first, we need to get a reference
to it:





bucket = conn.get_bucket('mybucket.example.com')





And then to list the contents:





[k.name for k in bucket.list()]





['cheesehop.txt', 'parrot.txt']


Uploading a file is a straightforward process. First, we need to get a reference to the
bucket that we want to put it in, and then we need to create a Key object, which will
represent our object in the bucket:





bucket = conn.get_bucket('mybucket.example.com')








from boto.s3.key import Key








key = Key(bucket)





Next, we have to set the Key name and then upload our file data:





key.key = 'lumberjack_song.txt'








key.set_contents_from_filename('~/lumberjack_song.txt')





The boto package will automatically set the Content-Type when it uploads a
file like this, and it uses the same mimetypes module that we used earlier for
determining a type.

Free download pdf