利用flask进行Web开发,Web网页呈现以下淡水鱼数据。 已知淡水鱼数据 data = [ ['f1','鲤鱼','杂食性',300], ['f2','草鱼','食草性',240], ['f3','鲫鱼','温水性',500], ['f4','鳙鱼','温水性',400], ['f5','黑鱼','肉食性',480], ]
时间: 2023-08-20 16:38:35 浏览: 177
可以按照以下步骤在 Flask 中呈现淡水鱼数据:
1. 在 Flask 中导入 render_template 函数和 request 对象:
```
from flask import Flask, render_template, request
```
2. 创建 Flask 应用程序:
```
app = Flask(__name__)
```
3. 创建路由,用于处理用户请求并返回响应:
```
@app.route('/')
def index():
data = [
['f1', '鲤鱼', '杂食性', 300],
['f2', '草鱼', '食草性', 240],
['f3', '鲫鱼', '温水性', 500],
['f4', '鳙鱼', '温水性', 400],
['f5', '黑鱼', '肉食性', 480],
]
return render_template('fish.html', data=data)
```
在这个路由中,我们将淡水鱼数据存储在变量 data 中,并将其作为参数传递给 render_template 函数。 render_template 函数将使用 Jinja2 模板引擎来呈现 HTML 页面。
4. 创建 HTML 模板 fish.html,用于呈现淡水鱼数据:
```
<html>
<head>
<title>淡水鱼数据</title>
</head>
<body>
<table>
<tr>
<th>ID</th>
<th>名称</th>
<th>食性</th>
<th>重量</th>
</tr>
{% for item in data %}
<tr>
<td>{{ item[0] }}</td>
<td>{{ item[1] }}</td>
<td>{{ item[2] }}</td>
<td>{{ item[3] }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
```
在这个模板中,我们使用了 for 循环来遍历淡水鱼数据,并将其呈现在一个 HTML 表格中。 使用双花括号 {{ }} 来包含需要在 HTML 中呈现的变量。
5. 运行 Flask 应用程序:
```
if __name__ == '__main__':
app.run()
```
在终端中输入 python app.py 命令来启动应用程序。
6. 在浏览器中访问 http://127.0.0.1:5000/,即可看到淡水鱼数据被呈现在 HTML 页面中了。
阅读全文
相关推荐













