Skip to content

Instantly share code, notes, and snippets.

@danielthiel
Last active August 29, 2015 13:56
Show Gist options
  • Save danielthiel/9295893 to your computer and use it in GitHub Desktop.
Save danielthiel/9295893 to your computer and use it in GitHub Desktop.
Uploading files to Amazon Web Service (AWS) S3 with BOTO. Init with AWS-ID, AWS-KEY.
from boto.s3.connection import S3Connection
from boto.s3.key import Key
# from boto.s3.connection import Location
class FilehandlerAmazon():
def __init__(self, aws_id, aws_key):
self.aws_id = aws_id
self.aws_key = aws_key
self.conn = S3Connection(self.aws_id, self.aws_key)
self.buckets = self.get_buckets()
def get_buckets(self):
bucketlist = []
for bucket in self.conn.get_all_buckets():
bucketlist.append(bucket.name)
return bucketlist
def lookup_bucket(self, bucketname):
bucketaccess = self.conn.lookup(bucketname)
if bucketaccess is None:
return False
return True
def upload_file(self, uploadfile, uploadkey, buckettype):
if not buckettype in self.buckets:
return False
bucket = self.conn.get_bucket(buckettype)
if bucket.get_key(str(uploadkey)) is not None:
return False # Filekey already exists
try:
k = Key(bucket)
k.key = str(uploadkey)
k.set_contents_from_filename(uploadfile)
k.set_canned_acl('public-read')
except:
return False
return True
def get_url(self, filekey, buckettype):
if not buckettype in self.buckets:
return None
bucket = self.conn.get_bucket(buckettype)
k = bucket.get_key(filekey)
if k is None:
return None
url = k.generate_url(0, query_auth=False, force_http=True)
return url
# def delete_file(self, filekey, buckettype):
# if not buckettype in self.buckets:
# return False
# bucket = self.conn.get_bucket(buckettype)
# bucket.delete_key(filekey)
# return True
AWS_S3 = {
u'key': u'secret_key',
u'id': u'secret_id',
u'buckets': {
u'bucket1': u'real_bucket_name'
}
}
def upload_file_and_get_url(path_to_my_file):
s3conn = FilehandlerAmazon(AWS_S3[u'id'], AWS_S3[u'key'])
s3conn.upload_file(path_to_my_file, u'some_filekey', AWS_S3[u'buckets']['bucket1'])
url = s3conn.get_link(u'some_filekey', u'bucket1')
return url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment