我正在使用boto3在AWS中显示有关我的s3存储桶的各种数据。 我在views.py中有以下代码来显示s3页面:
<div class="s3Items">
{% for bucket in buckets %}
<div class="s3Name">
<div id="left">
<h4 id='s3ItemName'>{{ bucketName }}</h4>
</div>
<div id="right">
<ul id='s3ItemDesc'>
<li>{{ createdAt }}</li>
<li>{{ totalSize }}/4GB</li>
<li>
<button type="button" name="button" class='button delete'>Delete</button>
</li>
</ul>
</div>
</div>
{% endfor %}
我试图在这样的模板中显示这些变量:
<div class="s3Items">
{% for bucket in buckets %}
<div class="s3Name">
<div id="left">
<h4 id='s3ItemName'>{{ bucket.name }}</h4>
</div>
<div id="right">
<ul id='s3ItemDesc'>
<li>{{ bucket.creation_date}}</li>
<li>{{ ??? }}/4GB</li>
<li>
<button type="button" name="button" class='button delete'>Delete</button>
</li>
</ul>
</div>
</div>
{% endfor %}
但显然这不起作用。如何在模板中迭代这些桶? 我也尝试了下面的工作,但它不起作用,因为我无法得到每个桶中所有文件的总大小:
yarn run
我可以在模板中创建一个新循环吗?或者我应该在python文件中创建它并在模板中调用它?我怎样才能做到这一点? 感谢
答案 0 :(得分:3)
您可以创建字典列表,然后可以在模板中迭代列表。
class s3(TemplateView):
template_name = 'project/s3.html'
def get_context_data(self, **kwargs):
context = super(s3, self).get_context_data(**kwargs)
data = []
aws = boto3.resource('s3')
buckets = aws.buckets.all()
for bucket in buckets:
bucket_data = {}
totalSize = 0
fileBuckets = boto3.resource('s3').Bucket(bucketName)
for file in fileBuckets.objects.all():
totalSize += file.size
bucket_data['bucketName'] = bucket.name
bucket_data['createdAt'] = bucket.createdAt
bucket_data['totalsize'] = totalSize
data.append(bucket_data)
context['buckets'] = data
return context
现在在模板中你可以迭代变量'buckets'。
<div class="s3Items">
{% for bucket in buckets %}
<div class="s3Name">
<div id="left">
<h4 id='s3ItemName'>{{ bucket.bucketName }}</h4>
</div>
<div id="right">
<ul id='s3ItemDesc'>
<li>{{ bucket.createdAt }}</li>
<li>{{ bucket.totalsize }}/4GB</li>
<li>
<button type="button" name="button" class='button
delete'>Delete</button>
</li>
</ul>
</div>
</div>
{% endfor %}