Flask Jinja2 for 循环

Flask Jinja2 for loop

我有这个 python 脚本,下面列出了实例 ID、状态和类型 AWS EC2 实例。正如您在下面看到的那样,这工作正常。

[root@localhost ec2]# cat ec2.py
#!/usr/bin/env python

import boto3

ec2client = boto3.client('ec2')
response = ec2client.describe_instances()

for reservation in response["Reservations"]:
        for instance in reservation["Instances"]:
                print "{0}\t{1}\t{2}".format(instance["InstanceId"], 
instance["State"]["Name"], instance["InstanceType"])

[root@localhost ec2]# ./ec2.py
i-xxxxxxxxxxxxxxxxx     stopped t2.small
i-yyyyyyyyyyyyyyyyy     running t2.medium
i-zzzzzzzzzzzzzzzzz     stopped t2.medium
i-bbbbbbbbbbbbbbbbb     stopped t2.small
i-ccccccccccccccccc     running t2.medium

现在我正在尝试使用 Flask 在网页中显示以上输出。但我是 收到错误说“”” 文件“/flask/ec2/app.py”,第 15 行,在 list_instances 中 实例 = 保留 ["Instances"] 类型错误:列表索引必须是整数,而不是 str """

这就是我到目前为止所做的

[root@localhost ec2]# cat app.py
import boto3
from flask import Flask, render_template

app = Flask(__name__)


ec2client = boto3.client('ec2')
response = ec2client.describe_instances()

@app.route("/")
def list_instances():
       reservations = response["Reservations"]
       instances = reservations["Instances"]
       return render_template("ec2.html", instances=instances)

if __name__ == '__main__':
    app.run(port=5000, debug=True, host="0.0.0.0")

[root@localhost ec2]# cat templates/ec2.html
<html>
<head>
       <title>EC2 List</title>
</head>

<body>
<h1>EC2 List</h1>
{% for instance in instances %}
<p>{{ instance }}</p>
{% endfor %}
</body>
</html>

有人可以帮我解决这个错误并获得所需的输出吗?

在您的示例中 reservations 是一个列表,因此您应该在尝试访问 reservation['Instances'].

之前使用 for reservation in reservations 对其进行迭代