Upload to Amazon S3 using Boto3 and return public url

Yaswanth Kumar picture Yaswanth Kumar · Nov 19, 2015 · Viewed 24.8k times · Source

Iam trying to upload files to s3 using Boto3 and make that uploaded file public and return it as a url.

class UtilResource(BaseZMPResource):
class Meta(BaseZMPResource.Meta):
    queryset = Configuration.objects.none()
    resource_name = 'util_resource'
    allowed_methods = ['get']

def post_list(self, request, **kwargs):

    fileToUpload = request.FILES
    # write code to upload to amazone s3
    # see: https://boto3.readthedocs.org/en/latest/reference/services/s3.html


    self.session = Session(aws_access_key_id=settings.AWS_KEY_ID,
                  aws_secret_access_key=settings.AWS_ACCESS_KEY,
                  region_name=settings.AWS_REGION)

    client = self.session.client('s3')
    client.upload_file('zango-static','fileToUpload')


    url = "some/test/url"
    return self.create_response(request, {
        'url': url // return's public url of uploaded file 
    })

I searched whole documentation I couldn't find any links which describes how to do this can someone explain or provide any resource where I can find the soultion?

Answer

Sam Keen picture Sam Keen · Jan 9, 2016

I'm in the same situation. Not able to find anything in the Boto3 docs beyond generate_presigned_url which is not what I need in my case since I have public readable S3 Objects.

The best I came up with is:

bucket_location = boto3.client('s3').get_bucket_location(Bucket=s3_bucket_name)
object_url = "https://s3-{0}.amazonaws.com/{1}/{2}".format(
    bucket_location['LocationConstraint'],
    s3_bucket_name,
    key_name)

You might try posting on the boto3 github issues list for a better solution.