Python 3 Boto 3, AWS S3: Get object URL

跟風遠走 提交于 2019-12-18 08:47:27

问题


I need to retrieve an public object URL directly after uploading a file, this to be able to store it in a database. This is my upload code:

   s3 = boto3.resource('s3')
   s3bucket.upload_file(filepath, objectname, ExtraArgs={'StorageClass': 'STANDARD_IA'})

I am not looking for a presigned URL, just the URL that always will be publicly accessable over https.

Any help appreciated.


回答1:


There's no simple way but you can construct the URL from the region where the bucket is located (get_bucket_location), the bucket name and the storage key:

bucket_name = "my-aws-bucket"
key = "upload-file"

s3 = boto3.resource('s3')
bucket = s3.Bucket(bucket_name)
bucket.upload_file("upload.txt", key)
location = boto3.client('s3').get_bucket_location(Bucket=bucket_name)['LocationConstraint']
url = "https://s3-%s.amazonaws.com/%s/%s" % (location, bucket_name, key)



回答2:


Since 2010 you can use a virtual-hosted style S3 url, i.e. no need to mess with region specific urls:

url = 'https://%s.s3.amazonaws.com/%s' % (bucket, key)

Moreover, support for the path-style model (region specific urls) continues for buckets created on or before September 30, 2020. Buckets created after that date must be referenced using the virtual-hosted model.

See also this blog post.




回答3:


Just a small note. The function call

location = 
    boto3.client('s3').get_bucket_location(Bucket=bucket_name['LocationConstraint']

may return location = None if the bucket is in the region 'us-east-1'. Therefore, I'd amend the above answer and add a line below that line:

if location == None: location = 'us-east-1'


来源:https://stackoverflow.com/questions/48608570/python-3-boto-3-aws-s3-get-object-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!