Getting file url after upload amazon s3 python, boto3

Viewed 15998

I'm just a new with boto3 and i can not understand how i can get URL link for file that i have just uploaded to s3 amazon.

Please clarify.

Thank you

import boto3

s3 = boto3.resource('s3')

data = open ('file.xlsx', 'rb')
s3.Bucket ('dimxxx1').put_object (Key='file.xlsx', Body=data)
4 Answers

First, the better way to upload would be:

import boto3
s3 = boto3.resource('s3')
s3.Bucket('dimxxx1').upload_file('/tmp/file.xlsx', 'file.xlsx')

To obtain the URL, you can construct it from the basic elements:

http://s3-REGION-.amazonaws.com/BUCKET-NAME/KEY

For example:

http://s3-ap-southeast-2.amazonaws.com/dimxxx1/file.xlsx

in python3,

url = f"https://{bucket}.s3.{region}.amazonaws.com/{folder}{file_name}"

Here is a fix for this issue to enable you get the URL of S3 file as suggested by this link. You basically have to generate a pre-signed URL for each S3 object you wish to provide access to. See the code below:

import boto3

# Get the service client.
s3 = boto3.client('s3')

# Generate the URL to get 'key-name' from 'bucket-name'
url = s3.generate_presigned_url(
    ClientMethod='get_object',
    Params={
        'Bucket': '<bucket-name>',
        'Key': '<key-name>'
    }
)

Change the <bucket-name> and <key-name> to your S3 bucket and the name of the file that was uploaded.

This is proper sequence with python formatter:

url = f"https://s3.{region}.amazonaws.com/{bucket}/{folder}...N/{file_name}"
Related