烧瓶阅读字典
Flask reading Dict
我想我在 Flask 中遗漏了一些东西。我想读我的字典,它是一个基本模板的静态文件,并使它与 Flask 一起出现。知道为什么我会出错吗?谢谢!
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def main():
return render_template('main.html, switch=switchList')
if __name__ == '__main__':
app.run(debug=True)
这是我的 main.html
<body>
{% block content %}
{% for switch in switches %}
Switch Name: {{ switch.name }} <br>
- Serial: {{ switch.serial }} <br>
- Reachable at: {{ switch.ip }} <br>
<br>
{% endfor %}
{% endblock %}
</body>
这是字典数据库
switchList = [
{
"name": "C9200",
"serial": "L3143S",
"ip": "192.168.1.1",
"check": True,
"total": 28,
"up": 10,
"down": 5,
"disabled": 13,
"capacity": 35
},
{
"name": "C9300",
"serial": "ASDSADA5",
"ip": "172.168.44.2",
"check": False,
"total": 48,
"up": 32,
"down": 6,
"disabled": 10,
"capacity": 67
},
]
Jinja 会将 python 对象渲染成 html。您的问题是您的字典没有作为 python 对象加载,因此它无法提供给您的页面。 解决方案,载入你的词典并通过你的html模板:
...
# Load your dict – be sure to enter the correct path
with open('static/switchList.json', 'r') as f:
switchList = json.loads(f)
@app.route('/')
def main():
return render_template('main.html', switch=switchList)
...
假设switchList
持有你想显示的数据,改变
return render_template('main.html, switch=switchList')
至
return render_template('main.html', switch=switchList)
我想我在 Flask 中遗漏了一些东西。我想读我的字典,它是一个基本模板的静态文件,并使它与 Flask 一起出现。知道为什么我会出错吗?谢谢!
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def main():
return render_template('main.html, switch=switchList')
if __name__ == '__main__':
app.run(debug=True)
这是我的 main.html
<body>
{% block content %}
{% for switch in switches %}
Switch Name: {{ switch.name }} <br>
- Serial: {{ switch.serial }} <br>
- Reachable at: {{ switch.ip }} <br>
<br>
{% endfor %}
{% endblock %}
</body>
这是字典数据库
switchList = [
{
"name": "C9200",
"serial": "L3143S",
"ip": "192.168.1.1",
"check": True,
"total": 28,
"up": 10,
"down": 5,
"disabled": 13,
"capacity": 35
},
{
"name": "C9300",
"serial": "ASDSADA5",
"ip": "172.168.44.2",
"check": False,
"total": 48,
"up": 32,
"down": 6,
"disabled": 10,
"capacity": 67
},
]
Jinja 会将 python 对象渲染成 html。您的问题是您的字典没有作为 python 对象加载,因此它无法提供给您的页面。 解决方案,载入你的词典并通过你的html模板:
...
# Load your dict – be sure to enter the correct path
with open('static/switchList.json', 'r') as f:
switchList = json.loads(f)
@app.route('/')
def main():
return render_template('main.html', switch=switchList)
...
假设switchList
持有你想显示的数据,改变
return render_template('main.html, switch=switchList')
至
return render_template('main.html', switch=switchList)