Created
August 28, 2015 15:34
-
-
Save Eimis/6a0aa8e7f4ed20fdd29c to your computer and use it in GitHub Desktop.
AWS upload implementation
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
''' | |
Functionality related to AWS file uploads. Separate module was created to | |
avoid circular imports and for better project structure | |
''' | |
import os | |
import random | |
import string | |
import urlparse | |
from django.conf import settings | |
import boto | |
from boto.s3.key import Key | |
def upload_file_to_aws(user_id, file_to_upload=None, previous_image_url=None): | |
''' | |
A function to upload images to our Amazon S3 server. | |
If file_to_upload keyword will not be provided, an existing image will | |
be deleted. If preiovus_image_url and file_to_upload will be provided, an | |
existing image will be deleted and a new one will be uploaded. If there's | |
a file_to_upload, but no previous_image_url, an image will simply be | |
uploaded. | |
''' | |
# try/except is for debugging purposes, because for some reason errors | |
# fail silently in boto: | |
try: | |
# connect to the bucket | |
bucket_name = settings.BUCKET_NAME | |
conn = boto.connect_s3( | |
settings.AWS_SECRET_ACCESS_KEY, | |
settings.AWS_ACCESS_KEY_ID | |
) | |
bucket = conn.get_bucket(bucket_name) | |
# remove old image: | |
if previous_image_url: | |
path = urlparse.urlparse(previous_image_url).path | |
previous_key = bucket.get_key(path) | |
bucket.delete_key(previous_key) | |
if file_to_upload: | |
key = 'property_images/{0}/{1}'.format( | |
user_id, | |
file_to_upload.name | |
) | |
key_exists = bucket.get_key(key) | |
# create a key to keep track of our file in the storage | |
k = Key(bucket) | |
# file name already exists: | |
if key_exists: | |
file_name = os.path.splitext(file_to_upload.name)[0] | |
file_extension = os.path.splitext(file_to_upload.name)[1] | |
random_hash = ''.join( | |
random.choice(string.lowercase) for i in range(10) | |
) | |
key = 'property_images/{0}/{1}'.format( | |
user_id, | |
file_name + '-' + random_hash + file_extension | |
) | |
k.key = key | |
temp_file = file_to_upload.temporary_file_path() | |
k.set_contents_from_filename(temp_file) | |
url = k.generate_url(expires_in=0, query_auth=False) | |
# 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() | |
return url | |
except Exception as e: | |
print(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment