Last active
December 18, 2015 10:29
-
-
Save ratpik/5768818 to your computer and use it in GitHub Desktop.
Utility function that helps upload files to S3 using python and boto
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#s3_object_key is the file path relative to the your S3 URL where you want to store the file | |
Eg. | |
s3_object_key = '%s/%s' %(settings.USER_PROFILE_PICTURE_DIR, filename) | |
#file is the file that you have create locally either in ephermal storage (Like the Heroku Dyno) or permanent storage like your local file system | |
#Write to local storage | |
Eg. | |
avatar = urlopen(url).read() #Pick a random file on the internet | |
fout = open(os.path.join(filepath, filename), "wb") | |
fout.write(avatar) | |
fout.close() | |
def push_picture_to_s3(s3_upload_key, file): | |
try: | |
import boto | |
from boto.s3.key import Key | |
bucket_name = settings.AWS_STORAGE_BUCKET_NAME | |
# connect to the bucket | |
conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, | |
settings.AWS_SECRET_ACCESS_KEY) | |
bucket = conn.get_bucket(bucket_name) | |
# create a key to keep track of our file in the storage | |
k = Key(bucket) | |
k.key = s3_upload_key | |
k.set_contents_from_filename(file) | |
# we need to make it public so it can be accessed publicly | |
# using a URL like http://s3.amazonaws.com/bucket_name/key | |
k.make_public() | |
# remove the file from the web server | |
os.remove(file) | |
except Exception: | |
raise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment