Flask 自定义路由转换器

步骤

  1. 创建自定义转换器类

    • 继承 werkzeug.routing.BaseConverter。
    • 实现 to_python 和(可选)to_url 方法。
  2. 将转换器注册到 Flask 应用

  3. 在路由中使用转换器

示例

创建转换器

假设需要自定义一个转换器 FourDigitYearConverter,用于匹配四位年份。

python 复制代码
# converters.py



from werkzeug.routing import BaseConverter

class FourDigitYearConverter(BaseConverter):
    def __init__(self, url_map):
        super().__init__(url_map)
        self.regex = r'\d{4}'  # 匹配四位数字

    def to_python(self, value):
        return int(value)  # 转换为整数

    def to_url(self, value):
        return f"{value:04d}"  # 确保是四位数字
注册转换器

在 Flask 应用中注册转换器:

python 复制代码
from flask import Flask
from converters import FourDigitYearConverter

app = Flask(__name__)

# 注册转换器
app.url_map.converters['yyyy'] = FourDigitYearConverter

定义路由

python 复制代码
@app.route('/year/<yyyy:year>/')
def year_view(year):
    return f"The year is {year}."
测试路由

访问 /year/2024/ 时:

  • URL 参数 2024 被捕获并转换为整数 2024。
反向生成 URL
python 复制代码
with app.test_request_context():
    url = flask.url_for('year_view', year=2024)
    print(url)  # 输出:/year/2024/
相关推荐
Want5951 小时前
Python跳动的爱心②
开发语言·python·数学建模
田里的水稻1 小时前
PyTorch_TensorBoard展示
人工智能·pytorch·python·深度学习·神经网络
环境栈笔记1 小时前
指纹浏览器 WebRTC 怎么设置?从 ICE 候选、代理出口到功能验证
前端·人工智能·后端·自动化
张张123y2 小时前
后端第九课:部署上线(把你的 FastAPI 后端真正跑起来给别人用)
python·docker·部署·fastapi
云勤通2 小时前
智慧后勤系统哪家定制能力强
大数据·python
想七想八不如114082 小时前
元学习简单入门
人工智能·pytorch·python·深度学习·学习·机器学习
一只小猪妖2 小时前
分布式唯一 性ID生成方法
后端
Zucker n2 小时前
一款适合研究生科研工作安排的日历
linux·数据库·python
小蒜学长2 小时前
微信小程序-高校自习室管理系统(代码+数据库+LW)
java·spring boot·后端·微信小程序·自习室管理