Using Amazon s3 boto library, how can I get the URL of a saved key?

PythonAmazon S3Boto

Python Problem Overview


I am saving a key to a bucket with:

	key = bucket.new_key(fileName)
	key.set_contents_from_string(base64.b64decode(data))
	key.set_metadata('Content-Type', 'image/jpeg')
	key.set_acl('public-read')

After the save is successful, how can I access the URL of the newly created file?

Python Solutions


Solution 1 - Python

If the key is publicly readable (as shown above) you can use Key.generate_url:

url = key.generate_url(expires_in=0, query_auth=False)

If the key is private and you want to generate an expiring URL to share the content with someone who does not have direct access you could do:

url = key.generate_url(expires_in=300)

where expires is the number of seconds before the URL expires. These will produce HTTPS url's. If you prefer an HTTP url, use this:

url = key.generate_url(expires_in=0, query_auth=False, force_http=True)

Solution 2 - Python

For Boto3, you need to do it the following way...

import boto3

s3 = boto3.client('s3')
url = '{}/{}/{}'.format(s3.meta.endpoint_url, bucket, key)

Solution 3 - Python

import boto
from boto.s3.connection import S3Connection

conn = S3Connection('AWS_ACCESS_KEY', 'AWS_SECRET_KEY')

secure_https_url = 'https://{host}/{bucket}/{key}'.format(
    host=conn.server_name(),
    bucket='name-of-bucket',
    key='name_of_key')

http_url = 'http://{bucket}.{host}/{key}'.format(
    host=conn.server_name(),
    bucket='name-of-bucket',
    key='name_of_key')

That's how I did it in boto 2.23.0 for a public URL. I couldn't get the expires_in=None argument to work.

Note that for HTTPS you can't use a subdomain.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionS-K'View Question on Stackoverflow
Solution 1 - PythongarnaatView Answer on Stackoverflow
Solution 2 - PythontreecoderView Answer on Stackoverflow
Solution 3 - Pythonkumar303View Answer on Stackoverflow