如何使用 django-storages 生成预签名的 S3 url?

use*_*284 14 python django boto3 python-django-storages

我有一个 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)
Run Code Online (Sandbox Code Playgroud)

视图.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)

Run Code Online (Sandbox Code Playgroud)

use*_*284 14

事实证明,您不需要使用 boto3 来生成预签名 url。Django-storages 抽象了整个过程。您可以简单地访问url上的属性FileField,如下例所示:

document_form = DocumentForm.objects.get(pk=1)
url = document_form.docfile.url
Run Code Online (Sandbox Code Playgroud)

- - 编辑 - -

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