Python flask入门
- 一、路由
-
- [1.1 常规路由](#1.1 常规路由)
- [1.2 动态路由](#1.2 动态路由)
- [1.3 路由的其他高级用法](#1.3 路由的其他高级用法)
- 二、变量规则
-
- [2.1 示例1:字符串类型(默认)](#2.1 示例1:字符串类型(默认))
- [2.2 示例2:整数类型](#2.2 示例2:整数类型)
- [2.3 示例3:路径类型](#2.3 示例3:路径类型)
- 三、自定义转换器
-
- [3.1 核心组件详解](#3.1 核心组件详解)
- [3.2 工作流程详解](#3.2 工作流程详解)
- 四、form表单
-
- [4.1 表单的三大组成部分](#4.1 表单的三大组成部分)
- 五、request请求
- 六、重定向
- 七、abort函数
- 八、综合板块
在了解Flask框架之前,强烈建议跟着官网教程及说明进行学习:https://dormousehole.readthedocs.io/en/latest/tutorial/layout.html
一、路由
1.1 常规路由
@app.route('/')
这是一个 装饰器(Decorator),用于将 URL 路径与 Python 函数绑定。'/'
代表 根路径(主页),例如访问 http://localhost:5000/ 时会触发 hello() 函数,hello() 函数又会返回 'Hello, World!',浏览器会显示该字符串。
@app.route('/first')
定义路由 /first
,访问 http://localhost:5000/first 时会调用 first() 函数,first() 函数又会返回 'first路由',浏览器会显示该字符串。
当用户访问某个 URL(如 / 或 /first),Flask 会查找匹配的路由,并执行对应的函数。
函数的返回值(字符串、HTML、JSON 等)会作为 HTTP 响应返回给浏览器。
python
from flask import Flask
# 从flask库中导入Flask类函数
app = Flask(__name__)
# 既然Flask是类函数,那就要实例化,app就是实例化的对象。其中__name__ 是一个 Python 特殊变量,表示当前模块的名称。
@app.route('/')
# 1、这是一个装饰器(decorator),是 Python 的一个特殊语法。
# 2、@app.route() 装饰器将 URL 路径与下面的函数(def)绑定在一起。
# 3、此代码中:'/' 表示网站的根路径(即主页),当代码运行时,会调用hello函数。
# 4、@app.route('/')就是路由。
def hello():
return 'Hello, World!'
@app.route('/first')
# 1、此处定义了first路由,装饰器地址与定义的函数一致
# 2、当页面加载first url时,会调用first函数
def first():
return 'first路由'
if __name__=='__main__':
app.run()
# app.run() 是 Flask 提供的 开发服务器启动方法,主要功能包括:
# 1、启动一个本地 Web 服务器(默认地址:http://127.0.0.1:5000/)。
# 2、监听 HTTP 请求,并根据定义的路由(@app.route)调用对应的函数。
# 3、提供调试信息(如访问日志、错误提示等)。
1.2 动态路由
(1) 默认字符串类型 <variable>
(2) 整数类型 <int:variable>
(3) 浮点数类型 <float:variable>
python
@app.route('/user/<id>')
def index(id):
if id == '1':
return '返回 1'
if id == str(2):
return '返回 str(2)'
# 1、访问 /user/1 → 返回 '返回 1'
# 2、访问 /user/2 → 返回 '返回 str(2)'
# 3、访问 /user/abc → 无匹配条件,返回空响应(可优化)
# (1) 默认字符串类型 <variable>
@app.route('/user/<username>')
def show_user(username):
return f'用户名: {username}'
# 1、/user/alice → 用户名: alice
# 2、/user/123 → 用户名: 123
# (2) 整数类型 <int:variable>
@app.route('/post/<int:post_id>')
def show_post(post_id): # post_id 是整数
return f'文章ID: {post_id}'
# 1、/post/42 → 文章ID: 42
# 2、/post/abc → 404 错误(不匹配)
# (3) 浮点数类型 <float:variable>
@app.route('/weight/<float:kg>')
def show_weight(kg):
return f'重量: {kg} 千克'
# 1、/weight/5.2 → 重量: 5.2 千克
1.3 路由的其他高级用法
(1) 多规则路由
(2) HTTP 方法限制
GET:用于 请求数据(如加载页面、搜索)
POST:用于 提交数据(如登录、注册、上传文件)
python
(1) 多规则路由
@app.route('/')
@app.route('/home')
def home():
return '首页'
# 访问 / 或 /home 均返回 '首页'
(2) HTTP 方法限制
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return '处理登录'
return '显示登录表单'
# 1、/login 路由可以同时处理 GET 和 POST 请求。
# 2、根据请求方法的不同,执行不同的逻辑(例如:GET 显示登录表单,POST 处理登录数据)。
二、变量规则
变量规则是 Flask 路由系统中用于动态匹配 URL 部分的关键特性,它允许你在 URL 中定义可变部分,并将这些部分作为参数传递给视图函数。
2.1 示例1:字符串类型(默认)
python
@app.route('/user/<username>')
def show_user(username):
return f"Hello, {username}!"
匹配 /user/john → username="john"
不匹配 /user/john/(因为默认不允许斜杠)
2.2 示例2:整数类型
python
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f"Post ID: {post_id}, Type: {type(post_id)}"
匹配 /post/42 → post_id=42(整数)
不匹配 /post/abc(因为无法转换为整数)
2.3 示例3:路径类型
python
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
return f"Subpath: {subpath}"
匹配 /path/one/two/three → subpath="one/two/three"
三、自定义转换器
需要知道<>
是提取参数的作用
那么例如<int:id>
中的int
就是转换器
Flask 的自定义转换器基于== Werkzeug== 的 BaseConverter
类,其核心由三部分组成:
- 正则表达式:定义 URL 变量部分的匹配规则
- to_python 方法:将 URL 字符串转换为 Python 对象
- to_url 方法:将 Python 对象转换回 URL 字符串
python
from werkzeug.routing import BaseConverter
class RegexConverter(BaseConverter):
def __init__(self, url_map, *items):
super(RegexConverter, self).__init__(url_map)
self.regex = items[0]
app.url_map.converters['regex'] = RegexConverter
@app.route('/regex/<regex("[a-z]{3}"):value>')
def show_regex(value):
return f'Value: {value}'
3.1 核心组件详解
- DynamicRegexConverter 类
python
class DynamicRegexConverter(BaseConverter):
继承自 BaseConverter,这是所有Flask转换器的基类,主要目的是允许在路由定义中动态指定正则表达式。
- init 方法
python
def __init__(self, url_map, *args):
super().__init__(url_map)
self.regex = args[0] # 从路由定义中获取正则表达式
url_map: Flask自动传入的URL映射对象
*args: 捕获所有额外的位置参数
args[0]: 获取路由定义中传入的第一个参数(即正则表达式字符串)
- 转换器注册
python
app.url_map.converters['dregex'] = DynamicRegexConverter
将自定义转换器注册到Flask应用中,dregex是转换器的名称,将在路由中使用
- 路由定义
python
@app.route('/product/<dregex("[A-Z]{3}-\d{4}"):product_code>')
分解路由参数部分:
<dregex("[A-Z]{3}-\d{4}"):product_code>
dregex: 使用的转换器名称
A-Z\]{3}-\\d{4}: 传递给转换器的正则表达式参数 product_code: 视图函数接收的参数名 ### 3.2 工作流程详解 1. 当访问 /product/ABC-1234 时: * 路由匹配阶段: Flask 看到 dregex 转换器,会使用 "\[A-Z\]{3}-\\d{4}" 作为正则表达式,检查 "ABC-1234" 是否匹配该模式。 * 正则表达式解析: \[A-Z\]{3}: 3个大写字母 → "ABC" -: 连字符 → "-" \\d{4}: 4个数字 → "1234" * 参数传递: 将 "ABC-1234" 作为 product_code 参数传递给视图函数 2. 如果访问无效URL如 /product/abc-123: * 正则匹配失败(需要大写字母) * Flask 自动返回 404 Not Found ## 四、form表单 想象表单就像你去银行填的表格: 表格纸 = 标签 填写项 = 字段(姓名、电话等) 提交按钮 = 柜台工作人员收走表格 ### 4.1 表单的三大组成部分 1. 前端部分(HTML) ```html