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/
相关推荐
geovindu3 小时前
python: Memento Pattern
开发语言·python·设计模式·备忘录模式
苍何3 小时前
字节发力,豆包大模型2.0 震撼来袭(附 Trae 实测)
后端
苍何3 小时前
不会剪辑的人,开始用 AI 批量出爆款了
后端
苍何3 小时前
百度 APP 正式接入 OpenClaw,所有人限时免费!
后端
寻星探路4 小时前
【JVM 终极通关指南】万字长文从底层到实战全维度深度拆解 Java 虚拟机
java·开发语言·jvm·人工智能·python·算法·ai
lbb 小魔仙4 小时前
【Java】Java 实战项目:手把手教你写一个电商订单系统
android·java·python
岱宗夫up4 小时前
FastAPI入门(上篇):快速构建高性能Python Web API
开发语言·前端·python·fastapi
Dxy12393102164 小时前
中文乱码恢复方案
开发语言·python
rongyili885 小时前
Dify 外部知识库集成 Milvus 实战指南
开发语言·python·milvus
Hello eveybody5 小时前
什么是动态规划(DP)?(Python版)
python·动态规划