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/
相关推荐
用户83562907805112 小时前
使用 Python 在 Excel 中添加和自定义迷你图
后端·python
码事漫谈12 小时前
给AI看一颗❤️,它就开始写递归了
后端
用户83562907805112 小时前
使用 Python 在 Excel 图表中添加趋势线与回归方程
后端·python
你三大爷13 小时前
Netty / Kafka / Redis 保序问题的源码对比与 NIO 框架主流解法
后端·架构
特立独行的猫A13 小时前
一份 Markdown 发十个平台:cspub 一稿多投
java·后端·python
3DGISer13 小时前
不透明物体的渲染算法
后端
深蓝AI13 小时前
HTTPX 超时 1 秒,接口为何还能跑 2.4 秒?
python
CyrusYiVPP13 小时前
哪个用户会再来买?RFM模型+plotly画出用户分层,数据分析实战第2期
人工智能·python
ServBay13 小时前
从代码到上线,Cursor Live Apps 能替独立开发者做什么
后端·ai编程·cursor
程序员cxuan13 小时前
LobeHub 是真的夯,简直 Super-Agent 最佳实现。
人工智能·后端·程序员