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/
相关推荐
Lucky高13 分钟前
Pandas库入门
python·pandas
程序猿DD17 分钟前
JUnit 5 中的 @ClassTemplate 实战指南
java·后端
小鸡吃米…25 分钟前
Python PyQt6教程三-菜单与工具栏
开发语言·python
Victor35640 分钟前
Netty(14)如何处理Netty中的异常和错误?
后端
Jack电子实验室1 小时前
【杭电HDU】校园网(DeepL/Srun)自动登录教程
python·嵌入式硬件·计算机网络·自动化
Victor3561 小时前
Netty(13)Netty中的事件和回调机制
后端
木头左1 小时前
二值化近似计算在量化交易策略中降低遗忘门运算复杂度
python
Jelena157795857921 小时前
Java爬虫淘宝拍立淘item_search_img拍接口示例代码
开发语言·python
郝学胜-神的一滴1 小时前
Python数据模型:深入解析及其对Python生态的影响
开发语言·网络·python·程序人生·性能优化