Storing your python project static and media files on Amazon S3
import boto3
from botocore.client import Config
from botocore.exceptions import NoCredentialsError
def upload_to_aws(file, filename, path=None, set_unique_filename=False ):
if set_unique_filename :
filename, file_extension = os.path.splitext(filename)
filename = filename + "_" + str(uuid.uuid4()) + file_extension
if path:
path+=str(filename)
else:
path = AWS_FILE_PATH + filename
try:
s3 = boto3.resource(
's3',
aws_access_key_id=settings.AWS_ACCESS_KEY,
aws_secret_access_key=settings.AWS_SECRET_KEY,
config=Config(signature_version='s3v4')
)
s3.Bucket(settings.AWS_STORAGE_BUCKET_NAME).put_object(Key=path ,Body=file )
# print("Uploaded. " )
# return [True, settings.AWS_S3_CUSTOM_DOMAIN + path]
return [True, path]
except Exception as e:
# raise e
print("Error: failed to upload file.\n", e)
return [False, None]