How to get AWS S3 object Location/URL using pyhton 3.8?

為{幸葍}努か 提交于 2020-12-13 03:20:40

问题


I am uploading a file to AWS S3 using AWS Lambda function (Python3.8) with the following code.

   file_obj = open(filename, 'rb')

   s3_upload = s3.put_object( Bucket="aaa", Key="aaa.png", Body=file_obj)
   
   return {
   'statusCode': 200,
   'body': json.dumps("Executed Successfully")
   }

I want to get the location/url of the S3 object in return. In Node.js we use the .location parameter for getting the object location/url.

Any idea how to do this using python 3.8?


回答1:


The url of S3 objects has known format and follows Virtual hosted style access:

https://bucket-name.s3.Region.amazonaws.com/keyname

Thus, you can construct the url yourself:

bucket_name = 'aaa'
aws_region = boto3.session.Session().region_name
object_key = 'aaa.png'

s3_url = f"https://{bucket_name}.s3.{aws_region}.amazonaws.com/{object_key}"

return {
   'statusCode': 200,
   'body': json.dumps({'s3_url': s3_url})
}


来源:https://stackoverflow.com/questions/64980652/how-to-get-aws-s3-object-location-url-using-pyhton-3-8

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