python - django 从列表中下载文件(s3 作为后端)
问题描述
我需要列出一个包含 S3 存储桶内容的 html 表,并启用下载文件的选项。为此,我已经完成了以下操作:代码正确显示了存储桶文件的列表,但我不确定如何编写代码来下载文件。
库存.html:
{% block title %} title{% endblock %}
{% block content %}
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Date <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 <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 上的列表包含对象列表,它不是静态内容。
任何其他方式来做到这一点,我很感激。太感谢了。
解决方案
您可以返回重定向,使用正确的 ACL 它应该开始下载
return HttpResponseRedirect(url)
推荐阅读
- excel - 将值从一张纸移动到另一张纸
- python - 如何重置和修复我的路径,以便 java 和 python 可以再次工作?
- laravel - Laravel 8 Yajra DataTable 在同一页面刷新
- android - 如果值不存在,则忽略 moshi 中的属性
- python - 帮助在 python 程序中编码,确定集合的体重指数
- haskell - Haskell Fractional 无法推断 (RealFrac a) 由于使用“round”而产生
- deep-learning - PyTorch Batch 屏蔽选择实现
- arrays - 如何打印嵌套混合对象和数组的所有值?
- jquery - Api 与 swal 一起命中
- r - 将列转换为具有 r 条件的行