6

我有一个 Django 表单,它通过 django-storages 库将文件保存到 s3 并且工作正常。如何生成并返回预签名的 url,以便用户可以在上传后临时访问文件?这是由 django-storages 抽象的还是我必须使用 boto3 api?

我已经花了几个小时浏览 Django-storages 文档,但是目前还不是很清楚如何做到这一点..

表格.py

class DocumentForm(forms.Form):
    docfile = forms.FileField(
        label='Select a file',
        help_text='max. 42 megabytes'
    )
   name = models.CharField(max_length=20)
   uploaded_at = models.DateTimeField(auto_now_add=True)

视图.py

def upload_file(request):
   if request.method == 'POST:
      form = DocumentForm(request.POST)
      if form.is_valid():
         form.save()
         url = #generate pre-signed url of uploaded file here
         return render(request, 'upload_response.html', url)

4

2 回答 2

5

事实证明,您不需要使用 boto3 来生成预签名的 url。Django-storages 抽象了整个过程。您可以按如下方式简单地生成它docfile.url

- - 编辑 - -

作为参考,这里是为您生成预签名 url 的 S3 存储类方法 https://github.com/jschneier/django-storages/blob/770332b598712da27ecdba75c9e202ad6a1a8722/storages/backends/s3boto3.py#L554

于 2021-02-18T16:30:34.117 回答
2

这是在 S3 中为对象生成预签名 url 的示例代码

import boto3

client = boto3.client('s3')
response = client.generate_presigned_url('get_object',Params={'Bucket': bucket_name,
                                                              'Key': objectpath},
                                         HttpMethod="GET", ExpiresIn=expires_in)
于 2020-10-09T16:56:49.957 回答