Created
March 22, 2019 00:38
-
-
Save gilsonbp/4281ccfdc3edf5a599a44669939c4c7d to your computer and use it in GitHub Desktop.
Implements sending files to S3 using Boto3 and the same django-storages parameters.
This file contains hidden or 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
import boto3 | |
from boto3.s3.transfer import S3Transfer | |
from django.conf import settings | |
__author__ = "Gilson Paulino" | |
__date__ = "Created by 21/03/19" | |
__copyright__ = "Copyright 2019" | |
__email__ = "[email protected]" | |
class GpBoto3(object): | |
""" | |
Implements sending files to S3 using Boto3 and the same django-storages | |
parameters. It is possible to return complete URLs for each file in a | |
natural way with `obj.file_field.url` | |
""" | |
def __init__(self): | |
super(GpBoto3, self).__init__() | |
""" Defining the bucket region """ | |
self._bucket_region = 'us-west-2' | |
""" | |
Searching for authentication data in settings according to | |
django-storages | |
""" | |
self._client = boto3.client( | |
's3', | |
self._bucket_region, | |
aws_access_key_id=settings.AWS_ACCESS_KEY_ID, | |
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY | |
) | |
self._transfer = S3Transfer(self._client) | |
""" Bucket name according to django-storages """ | |
self._bucket = settings.AWS_STORAGE_BUCKET_NAME | |
""" | |
Checks whether an ACL has been set in django-storages, otherwise | |
arrow as public-read | |
""" | |
if settings.AWS_DEFAULT_ACL: | |
self._default_acl = settings.AWS_DEFAULT_ACL | |
else: | |
self._default_acl = 'public-read' | |
def send(self, local_path, s3_path): | |
""" | |
Send the file | |
:param local_path: Location of the local file that will be sent | |
:param s3_path: Location of the S3 bucket file after submission | |
:return: S3 direct url to uploaded file | |
""" | |
self._transfer.upload_file( | |
local_path, | |
self._bucket, | |
s3_path, | |
extra_args={'ACL': self._default_acl} | |
) | |
return self._url(self._bucket, s3_path) | |
def _url(self, bucket_name, s3_path): | |
""" | |
Direct file url in S3. | |
It is appropriate to use the Django features built into | |
django-storages using `obj.file_field.url` | |
""" | |
return "{}/{}/{}".format( | |
self._client.meta.endpoint_url, | |
bucket_name, | |
s3_path | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment