Flask 第一个应用
Flask 第一个应用中文讲解
Flask 是一个轻量级的 Python Web 框架,适合快速构建 Web 应用。本文以中文详细讲解如何创建你的第一个 Flask 应用,涵盖项目搭建、基本代码实现、模板渲染、运行和调试,以及与 Chart.js 集成的简单示例,帮助初学者快速上手。本教程力求简洁清晰,结合之前的 Flask 安装和简介内容,重点放在实际操作和代码实现上,避免重复理论讲解。
1. 目标
通过本教程,你将:
- 创建一个简单的 Flask 应用,返回一个欢迎页面。
- 学习如何使用模板渲染动态 HTML。
- 实现一个与 Chart.js 集成的页面,展示动态图表。
- 了解运行和调试 Flask 应用的基本方法。
2. 准备工作
确保已完成以下准备(参考之前的安装讲解):
- Python 环境:已安装 Python 3.7+,并验证
python --version
和pip --version
。 - Flask 安装:已通过
pip install flask
安装 Flask。 - 虚拟环境(推荐):
python -m venv venv
source venv/bin/activate # Linux/macOS
venv\Scripts\activate # Windows
- 文本编辑器:如 VS Code、PyCharm 或任意支持 Python 的编辑器。
3. 创建第一个 Flask 应用
以下是创建第一个 Flask 应用的分步指南,展示一个简单的欢迎页面。
步骤 1:项目结构
创建一个项目目录,结构如下:
first_flask_app/
├── app.py
├── templates/
│ └── index.html
├── static/
│ └── css/
│ └── style.css
└── venv/
app.py
:主应用文件,包含 Flask 代码。templates/
:存放 HTML 模板。static/
:存放 CSS、JavaScript 等静态文件。venv/
:虚拟环境目录(已创建)。
步骤 2:编写 Flask 代码(app.py
)
from flask import Flask, render_template
# 创建 Flask 应用实例
app = Flask(__name__)
# 定义路由:首页
@app.route('/')
def home():
return render_template('index.html', title='欢迎使用 Flask', message='这是你的第一个 Flask 应用!')
# 运行应用
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
说明:
Flask(__name__)
:创建 Flask 实例,__name__
用于定位模板和静态文件。@app.route('/')
:定义根路径(/
),映射到home
函数。render_template
:渲染index.html
模板,传递title
和message
变量。app.run(debug=True)
:以调试模式运行,host='0.0.0.0'
允许外部访问,port=5000
指定端口。
步骤 3:创建 HTML 模板(templates/index.html
)
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<div class="container">
<h1>{{ title }}</h1>
<p>{{ message }}</p>
</div>
</body>
</html>
说明:
- 使用 Jinja2 模板语法(
{{ title }}
和{{ message }}
)显示动态内容。 url_for('static', filename='css/style.css')
:引用静态 CSS 文件。
步骤 4:添加 CSS 样式(static/css/style.css
)
body {
font-family: Arial, sans-serif;
background-color: #f3f4f6;
margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 50px auto;
padding: 20px;
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
text-align: center;
}
h1 {
color: #1f2937;
}
p {
color: #4b5563;
}
说明:简单的 CSS 样式美化页面,使用类 Tailwind 的配色和布局。
步骤 5:运行应用
- 确保在虚拟环境中(激活
venv
)。 - 运行 Flask 应用:
python app.py
- 打开浏览器,访问
http://127.0.0.1:5000
。 - 预期结果:看到标题“欢迎使用 Flask”和消息“这是一个简单的 Flask 应用!”。
4. 与 Chart.js 集成
为增强应用功能,我们添加一个路由和页面,使用 Chart.js 渲染柱状图,展示动态数据。
修改 app.py
from flask import Flask, render_template, jsonify
app = Flask(__name__)
# 首页
@app.route('/')
def home():
return render_template('index.html', title='欢迎使用 Flask', message='这是你的第一个 Flask 应用!')
# 图表页面
@app.route('/chart')
def chart():
return render_template('chart.html', title='销量数据可视化')
# 数据接口
@app.route('/api/data')
def get_data():
data = {
'labels': ['一月', '二月', '三月', '四月'],
'datasets': [{
'label': '2025 年销量',
'data': [65, 59, 80, 81],
'backgroundColor': 'rgba(59, 130, 246, 0.5)',
'borderColor': 'rgba(59, 130, 246, 1)',
'borderWidth': 1
}]
}
return jsonify(data)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
创建图表模板(templates/chart.html
)
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="container">
<h1>{{ title }}</h1>
<canvas id="myChart"></canvas>
<p><a href="{{ url_for('home') }}" class="text-blue-500">返回首页</a></p>
</div>
<script>
fetch('/api/data')
.then(response => response.json())
.then(data => {
const ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: data,
options: {
responsive: true,
plugins: {
title: { display: true, text: '2025 年月度销量' },
legend: { position: 'top' }
},
scales: {
y: { beginAtZero: true, title: { display: true, text: '销量 (单位)' } }
}
}
});
});
</script>
</body>
</html>
修改 index.html
添加导航
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<div class="container">
<h1>{{ title }}</h1>
<p>{{ message }}</p>
<p><a href="{{ url_for('chart') }}" class="text-blue-500">查看销量图表</a></p>
</div>
</body>
</html>
说明:
- 路由:添加
/chart
路由渲染图表页面,/api/data
返回 JSON 数据。 - 模板:
chart.html
使用 Chart.js 渲染柱状图,通过fetch
获取后端数据。 - 导航:在
index.html
和chart.html
中添加相互链接。 - 样式:复用
style.css
保持一致美观。 - 运行:访问
http://127.0.0.1:5000/chart
,查看柱状图。
5. 运行与调试
- 运行命令:
python app.py
- 默认在
http://127.0.0.1:5000
运行。 debug=True
启用热重载,修改代码后自动刷新。- 调试技巧:
- 检查 Flask 控制台输出,查看错误信息。
- 使用
app.logger.debug('消息')
记录调试信息。 - 确保
templates
和static
目录正确,路径错误会导致 404。
6. 扩展功能
为进一步增强应用,可尝试以下功能:
- 添加动态数据:
- 修改
/api/data
路由,从数据库(如 SQLite)或文件获取数据。 - 示例:
python import random @app.route('/api/data') def get_data(): data = { 'labels': ['一月', '二月', '三月', '四月'], 'datasets': [{ 'label': '2025 年销量', 'data': [random.randint(50, 100) for _ in range(4)], 'backgroundColor': 'rgba(59, 130, 246, 0.5)', 'borderColor': 'rgba(59, 130, 246, 1)', 'borderWidth': 1 }] } return jsonify(data)
- 添加表单:
- 使用 Flask-WTF 创建表单,允许用户输入数据。
- 安装:
pip install flask-wtf
。
- 集成数据库:
- 使用 Flask-SQLAlchemy 连接数据库(如 SQLite、MySQL)。
- 安装:
pip install flask-sqlalchemy
。
7. 注意事项
- 项目结构:
- 保持清晰的目录结构,
templates
和static
必须位于项目根目录。 - 静态文件通过
url_for
引用,避免硬编码路径。
- 调试模式:
debug=True
仅用于开发,生产环境中禁用以提高安全性和性能。- 生产部署推荐使用 Gunicorn:
bash pip install gunicorn gunicorn -w 4 -b 0.0.0.0:8000 app:app
- 安全性:
- 设置
app.config['SECRET_KEY']
用于 CSRF 保护:python app.config['SECRET_KEY'] = 'your-secret-key'
- 与 Chart.js 集成:
- 确保 Chart.js CDN 或本地文件正确加载。
- 数据接口(
/api/data
)返回的 JSON 格式需与 Chart.js 要求一致。 - 可使用
useMemo
(React 场景)或前端缓存优化性能。
- 常见问题:
- 模板未找到:确认
templates
目录存在,文件名正确。 - 端口冲突:修改
app.run(port=5001)
使用其他端口。 - 静态文件 404:检查
url_for
路径和static
目录。
8. 资源
- Flask 官方文档:https://flask.palletsprojects.com/
- Chart.js 文档:https://www.chartjs.org/docs/latest/
- 中文社区:搜索“Flask 入门教程”或参考掘金、知乎、CSDN。
如果需要更详细的讲解(如添加数据库、表单、用户认证或生产部署),请告诉我!