使用Boto3上传到Amazon S3并返回公共URL [英] Upload to Amazon S3 using Boto3 and return public url
问题描述
我正在尝试使用Boto3将文件上传到s3,并将该上传文件公开,并以url的形式返回.
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?
推荐答案
我处于相同的情况.在Boto3文档中找不到generate_presigned_url以外的任何内容,这对我来说不是我需要的,因为我有公共可读的S3对象.
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)
您可以尝试在 boto3 github问题列表中发布,以获得更好的解决方案.
You might try posting on the boto3 github issues list for a better solution.
这篇关于使用Boto3上传到Amazon S3并返回公共URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!