目录
一、Flask 框架
1. Flask 概述
Flask 是一个轻量级的 Python Web 框架,基于 Werkzeug(WSGI 工具库)和 Jinja2(模板引擎)。其核心特点包括:
-
轻量灵活:无强制依赖,可自由选择扩展库(如数据库ORM、表单验证)。
-
适合场景:中小型项目、微服务、API 开发。
-
核心特性:路由、模板渲染、请求上下文、会话管理。
2. 安装 Flask
指定更新源
pip3 config set global.index-url http://mirrors.aliyun.com/pypi/simple
信任更新源
pip3 config set install.trusted-host mirrors.aliyun.com
更新一下(默认为国外的更新源)
pip3 install --upgrade pip
pip install flask
# 安装表单处理扩展
3. 创建你的第一个 Flask 应用
# app.py
from flask import Flask # 导入 Flask 类
app = Flask(__name__) # 创建 Flask 应用实例,__name__ 用于确定资源路径
@app.route("/") # 定义路由:将根路径 '/' 绑定到视图函数
def hello():
return "Hello, World!" # 返回响应内容
if __name__ == "__main__": # 确保直接运行脚本时启动服务器
app.run(debug=True) # 启动开发服务器,debug=True 开启调试模式(自动重载代码)
运行结果:
访问 http://localhost:5000
,页面显示 "Hello, World!"。
4. 运行 Flask 应用
方式一:直接运行脚本
python app.py
方式二:通过环境变量启动
export FLASK_APP=app.py # 设置环境变量指定应用入口
export FLASK_DEBUG=1 # 开启调试模式(显示详细错误信息)
flask run # 启动服务器
5. Flask 路由与视图函数
(1)动态路由
捕获 URL 中的变量:
@app.route('/greet/<name>')
def greet(name):
return 'ni hao,{name}\n'
@app.route("/user/<username>") # <username> 捕获字符串变量
def show_user(username):
return f"User: {username}"
@app.route("/post/<int:post_id>") # <int:post_id> 捕获整数变量
def show_post(post_id):
return f"Post ID: {post_id}"
支持的类型:
-
string
:默认类型(不包含斜杠) -
int
:整数 -
float
:浮点数 -
path
:类似字符串,但允许斜杠 -
uuid
:UUID 字符串
(2)支持多种HTTP请求方法
from flask import request
@app.route("/login", methods=["GET", "POST"]) # 允许 GET 和 POST 请求
def login():
if request.method == "POST": # 处理 POST 请求(如表单提交)
return "处理登录请求"
return "显示登录表单" # 处理 GET 请求(如展示表单)
(3)使用 jinja2 模板渲染 HTML
步骤 1:创建模板文件
<!-- templates/index.html -->
<html>
<body>
<h1>Hello {{ name }}!</h1> <!-- {{ name }} 为变量占位符 -->
</body>
</html>
##{{ name }}:这个样式的一般都是模板,里面是变量名,调用的是jinjia模板
步骤 2:在视图函数中渲染模板
from flask import render_template
#把返回的内容交给模板处理
@app.route("/")
def index():
return render_template("index.html", name="Alice") # 传递变量 name,Flask会加载index.html模板
(4)模块继承与块
基模板(base.html):定义通用结构
<!-- templates/base.html -->
<html>
<head>
<title>{% block title %}{% endblock %}</title> <!-- 定义可替换的标题块 -->
</head>
<body>
{% block content %}{% endblock %} <!-- 定义可替换的内容块 -->
</body>
</html>
子模板(child.html):继承并填充块
<!-- templates/child.html -->
{% extends "base.html" %} <!-- 继承基模板 -->
{% block title %}主页{% endblock %} <!-- 填充标题块 -->
{% block content %} <!-- 填充内容块 -->
<h1>欢迎来到我的网站!</h1>
{% endblock %}
视图函数:
@app.route("/")
def home():
return render_template("child.html") # 渲染子模板
渲染结果:页面标题为“主页”,内容显示“欢迎来到我的网站!”。
6. Flask 表单处理与用户输入
(1)安装 Flask-WTF
pip install flask-wtf # 安装表单扩展库(集成 WTForms)
(2)创建一个简单的表单
--导入模块
from flask import Flask, render_template, request # 导入Flask框架核心组件:Flask类用于创建应用实例,render_template用于渲染HTML模板,request用于处理HTTP请求
from flask_wtf import FlaskForm # 从flask_wtf扩展导入FlaskForm基类,用于创建表单
from wtforms import StringField # 从wtforms库导入StringField类,用于创建文本输入字段
from wtforms.validators import DataRequired # 从wtforms库导入DataRequired验证器,确保字段有值
--应用配置与路由逻辑
app = Flask(__name__) # 创建Flask应用实例
app.secret_key ='s3cr3t' # 设置应用的密钥,用于CSRF保护和会话管理
class NameForm(FlaskForm): # 定义表单类,继承自FlaskForm
name = StringField('Name', validators=[DataRequired()]) # 创建文本输入字段,标签为'Name',并添加必填验证
@app.route('/', methods=['GET', 'POST']) # 定义根路由,支持GET和POST请求
def index(): # 视图函数
form = NameForm() # 实例化表单
if form.validate_on_submit(): # 检查表单是否通过验证并提交
return f'Hello, {form.name.data}!' # 如果通过,返回欢迎消息
return render_template('index.html', form=form) # 如果未提交或验证失败,渲染模板并传递表单实例
if __name__ == '__main__': # 确保应用作为主程序运行时启动
app.run(debug=True) # 启动开发服务器,开启调试模式
index.html 模块
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask Form</title> <!-- 页面标题 -->
</head>
<body>
<h1>Enter your name:</h1> <!-- 页面标题 -->
<form method="POST"> <!-- 创建POST请求表单 -->
{{ form.csrf_token }} <!-- 生成并插入CSRF令牌,防止跨站请求伪造 -->
<label for="name">Name:</label> <!-- 表单字段标签 -->
{{ form.name() }}<br><br> <!-- 渲染文本输入字段 -->
<button type="submit">Submit</button> <!-- 提交按钮 -->
</form>
{% if form.name.data %} <!-- 如果表单已提交且name字段有值 -->
<h2>Hello, {{ form.name.data }}!</h2> <!-- 显示欢迎消息 -->
{% endif %}
</body>
</html>
(3)表单验证
Flask 表单处理的强大之处在于其高效且灵活的验证机制。借助 wtforms
,开发者能够极为便捷地为表单字段配置多样化的验证规则,极大提升了表单数据的可靠性与安全性。例如,除了基础的 DataRequired()
(用于确保字段内容不为空,避免提交空白数据),还可运用以下规则:
Length(min=2, max=50)
:精准验证输入内容的长度,确保其介于 2 到 50 个字符之间,有效控制输入数据的长度范围,避免过长或过短的无效输入。Email()
:严格校验输入是否为符合规范的有效邮箱地址,这在用户注册、联系信息收集等场景中极为实用,能确保收集到的邮箱可正常使用。EqualTo('password')
:用于验证两个字段的值是否完全相等,典型应用场景是用户注册时的密码与确认密码字段,确保两次输入一致,避免因输入错误导致的密码设置问题。
二、 Flask 的项目结构与部署
1. 项目结构
/my_flask_app
/app
/templates
index.html
/static
/css
/js
__init__.py(初始化 Flask 应用)
routes.py(定义所有路由和视图函数)
forms.py(定义表单类)
run.py
######
/templates:存放所有 HTML 模板文件。
/static:存放静态文件(如 CSS、JS、图片等)。
2. 部署 Flask 应用
- Gunicorn:Python WSGI HTTP 服务器,用于生产环境部署。
- Nginx:作为反向代理,处理静态文件请求,转发动态请求到 Flask 应用。
gunicorn -w 4 run:app
##启动 4 工作线程的 Gunicorn 服务器,其中 run 指向 Flask 应用实例模块。
3. 小案例:简单博客应用
(1)项目结构
/simple_blog
/app
/templates
index.html
app.py
(2)app.py 代码
from flask import Flask, render_template, request
app = Flask(__name__)
# 存储所有文章
posts = []
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
posts.append({'title': title, 'content': content})
return render_template('index.html', posts=posts)
if__name__ == '__main__':
app.run(debug=True)
(3)index.html 模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Blog</title>
</head>
<body>
<h1>Welcome to the Blog!</h1>
<h2>Submit a Post</h2>
<form method="POST">
<label for="title">Title:</label>
<input type="text" id="title" name="title" required><br><br>
<label for="content">Content:</label>
<textarea id="content" name="content" required></textarea><br><br>
<button type="submit">Submit</button>
</form>
<h2>Posts:</h2>
<ul>
{% for post in posts %}
<li>
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
</li>
{% endfor %}
</ul>
</body>
</html>
(4)代码解析
- 数据存储:我们通过 Python 的 posts 列表存储所有提交的文章,每一篇文章由一个包含 title 和 content 的字典表示。
- 表单提交:当用户通过表单提交文章时,Flask 会将文章的标题和内容添加到 posts 列表中。
- 模板渲染:Flask 通过 render_template 将所有文章渲染到 index.html 模板中,使用
{% for post in posts %}
循环显示每一篇文章。
(5)运行博客应用
- 将 app.py 和 index.html 保存到相应文件夹中。
- 在命令行中运行 Flask 应用:
python app.py - 访问 http://127.0.0.1:5000/,你将看到一个简单的博客界面,能够提交文章并查看已发布的内容。