Wednesday, August 7, 2013

Manage AWS S3 buckets with Python - Part 2

Here is some more detail on working with S3 using Python.

1. Create a bucket in non-default location.

from boto.s3.connection import Location
#Display all available regions
print '\n'.join(i for i in dir(Location) if i[0].isupper())
#Make connection to S3
s3_conn=boto.connect_s3()
#Create bucket in South-East Asia region
s3_conn.create_bucket('nix-bucket091', location=Location.SAEast)
2. Upload a file to S3
from boto.s3.key import Key
#Create bucket object
bucket_name=s3_conn.get_bucket('nix-bucket091')
#Create Key object
s3_key=Key(bucket_name)
#Set key name attribute
s3_key.key='myfile'
#Create the object of the file you want to upload
fp=open('d:/take100.txt','r')
#Transfer the file
s3_key.set_contents_from_file(fp)
3. List all files in a bucket
#Create bucket objcet
mybucket=s3_conn.get_bucket('nix-bucket1981')
#Loop through all the files in the bucket
for bList in mybucket.list():
     print bList.name.encode('utf-8')

To learn Cloud Computing with AWS, Please get yourself enrolled here. This course is only for $10 with lifetime access of the material.

No comments:

Post a Comment