1.编程实现:利用flask进行Web开发,Web网页呈现以下淡水鱼数据。 已知淡水鱼数据 data = [ ['f1','鲤鱼','杂食性',300], ['f2','草鱼','食草性',240], ['f3','鲫鱼','温水性',500], ['f4','鳙鱼','温水性',400], ['f5','黑鱼','肉食性',480], ]
时间: 2023-10-23 07:07:55 浏览: 53
可以按照以下步骤进行实现:
1. 安装 Flask:在终端输入 `pip install flask` 即可安装 Flask。
2. 创建 Flask 应用程序:新建一个 Python 文件,引入 Flask 模块,创建 Flask 应用程序实例。
```python
from flask import Flask, render_template
app = Flask(__name__)
```
3. 定义路由:使用 `@app.route()` 装饰器定义路由,当用户访问该路由时,返回相应的 HTML 模板。
```python
@app.route('/')
def index():
data = [
['f1', '鲤鱼', '杂食性', 300],
['f2', '草鱼', '食草性', 240],
['f3', '鲫鱼', '温水性', 500],
['f4', '鳙鱼', '温水性', 400],
['f5', '黑鱼', '肉食性', 480],
]
return render_template('fish.html', data=data)
```
4. 创建 HTML 模板:在项目根目录下创建一个名为 templates 的文件夹,在该文件夹下创建 fish.html 文件,使用 jinja2 模板引擎渲染数据。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>淡水鱼数据</title>
</head>
<body>
<table>
<thead>
<tr>
<th>编号</th>
<th>名称</th>
<th>食性</th>
<th>重量(g)</th>
</tr>
</thead>
<tbody>
{% for item in data %}
<tr>
<td>{{ item[0] }}</td>
<td>{{ item[1] }}</td>
<td>{{ item[2] }}</td>
<td>{{ item[3] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
```
5. 运行应用程序:在终端输入 `python app.py`,即可运行该应用程序,访问 `http://127.0.0.1:5000/` 即可查看淡水鱼数据。
完整代码如下:
```python
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
data = [
['f1', '鲤鱼', '杂食性', 300],
['f2', '草鱼', '食草性', 240],
['f3', '鲫鱼', '温水性', 500],
['f4', '鳙鱼', '温水性', 400],
['f5', '黑鱼', '肉食性', 480],
]
return render_template('fish.html', data=data)
if __name__ == '__main__':
app.run()
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>淡水鱼数据</title>
</head>
<body>
<table>
<thead>
<tr>
<th>编号</th>
<th>名称</th>
<th>食性</th>
<th>重量(g)</th>
</tr>
</thead>
<tbody>
{% for item in data %}
<tr>
<td>{{ item[0] }}</td>
<td>{{ item[1] }}</td>
<td>{{ item[2] }}</td>
<td>{{ item[3] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)