2015-11-19 69 views
12

Iam尝试使用Boto3将文件上传到s3,并将上传的文件公开并将其作为网址返回。使用Boto3上传到Amazon S3并返回公开网址

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 
    }) 

我搜索整个文档,我找不到它描述了如何做到这一点可能有人解释或提供任何资源在那里我可以找到soultion任何联系?

+0

凡你能得到这个工作? – nadermx

+0

@nadermx我无法得到这项工作,你能帮助我吗? –

回答

18

我处于同样的情况。 无法在Boto3文档中找到generate_presigned_url之外的任何内容,这不是我需要的,因为我拥有公共可读的S3对象。

我想出的最好的是:

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 issues list发布一个更好的解决方案。

7

我有同样的问题。 假设你知道你要存储数据的存储桶名称,然后你可以使用以下命令:

import boto3 
from boto3.s3.transfer import S3Transfer 

credentials = { 
    'aws_access_key_id': aws_access_key_id, 
    'aws_secret_access_key': aws_secret_access_key 
} 

client = boto3.client('s3', 'us-west-2', **credentials) 
transfer = S3Transfer(client) 

transfer.upload_file('/tmp/myfile', bucket, key, 
        extra_args={'ACL': 'public-read'}) 

file_url = '%s/%s/%s' % (client.meta.endpoint_url, bucket, key) 
+1

你可以解释一下你的代码吗? – Whitecat

+0

谢谢,使用S3Transfer的upload_file中的extra_args是我通过会话为自定义端点创建客户端时需要联合使用的。 – madprops

1

我发现最好的解决办法仍然是使用generate_presigned_url,刚才说的Client.Config.signature_version需要被设置为botocore.UNSIGNED

以下返回没有签名的东西的公共链接。

config.signature_version = botocore.UNSIGNED 
boto3.client('s3', config=config).generate_presigned_url('get_object', ExpiresIn=0, Params={'Bucket': bucket, 'Key': key}) 

在boto3库中的相关讨论是: