首页 > 解决方案 > django 从列表中下载文件(s3 作为后端)

问题描述

我需要列出一个包含 S3 存储桶内容的 html 表,并启用下载文件的选项。为此,我已经完成了以下操作:代码正确显示了存储桶文件的列表,但我不确定如何编写代码来下载文件。

库存.html:

{% block title %} title{% endblock %}

{% block content %}
<table class="table table-striped">
  <thead>
    <tr>
      <th scope="col">Date&nbsp;<a href="?order_by=ord_date&direction=desc">{% load static %}<img src="{% static "arrow.png" %}" width="12" height="12" alt="order desc"></a><a href="?order_by=ord_date&direction=asc">{% load static %}<img src="{% static "sort-down.png" %}" width="12" height="12" alt="order asc"></a></th>

      <th scope="col">Name&nbsp;<a href="?order_by=ord_source&direction=desc">{% load static %}<img src="{% static "arrow.png" %}" width="12" height="12" alt="order desc"></a><a href="?order_by=ord_source&direction=asc">{% load static %}<img src="{% static "sort-down.png" %}" width="12" height="12" alt="order asc"></a></th>

      <th scope="col">Size</th>

      <th scope="col">Action</th>

    </tr>
  </thead>
  <tbody>  
     {% for item in items %}
        <tr>
          <td>{{ item.LastModified }}</td>
          <td>{{ item.Key }}</td>
          <td>{{ item.Size }}</td>
          <td><button type="Button" class="btn btn-secondary btn-sm"><a href="?key_download={{ item.Key }}">Download</button></a></td>
        </tr>
    {% endfor %}
</tbody>
</table>
{% endblock %}

视图.py:

client = boto3.client('s3')

def inventory(request):
    if request.GET.get('key_download'):
        url = client.generate_presigned_url('get_object', Params = { 
                                                                    'Bucket':'url_of_the_bucket',
                                                                    'Key':request.GET.get('key_download')},
                                                          ExpiresIn = 86400)

        return **"I don't know how I can return it"**
    else:
        fdc_inventories = client.list_objects_v2(Bucket='url_of_the_bucket')
        fdc_inventories['Contents'].sort(key=itemgetter('LastModified'), reverse=True)
        return render(request, 'inventory.html', {'items': fdc_inventories['Contents']})

所以我不确定如何退货。请记住,模板或 html 上的列表包含对象列表,它不是静态内容。

任何其他方式来做到这一点,我很感激。太感谢了。

标签: pythondjangodjango-viewsdjango-templatesboto3

解决方案


您可以返回重定向,使用正确的 ACL 它应该开始下载 return HttpResponseRedirect(url)


推荐阅读