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/
相关推荐
小村儿11 小时前
连载13- 内部Tools,Claude Code 怎么真正"动"你的代码
前端·后端·ai编程
IT_陈寒11 小时前
Python的线程池把我坑惨了,原来异步不是万能的
前端·人工智能·后端
夏语灬11 小时前
cryptography:Python 密码学标准库的终极选择
开发语言·python·密码学
郑洁文11 小时前
基于SpringBoot的商品仓库管理系统的设计与实现
java·spring boot·后端·仓库管理系统·商品仓库管理系统
该用户已不存在12 小时前
这9款开发工具夯爆了,用了都说好
后端·程序员·全栈
KeepPush12 小时前
Python迭代器与生成器:从原理到实战的深度解析
后端
CTA终结者12 小时前
期货开仓前保证金够吗:get_account 可用与占用字段对照
python·区块链
开源量化GO12 小时前
夜盘白盘衔接几分钟误下单:天勤交易时段与行情过滤
python·区块链
KeepPush12 小时前
Python itertools 深度指南:用迭代器代数写出更高效的代码
后端
辣椒思密达12 小时前
Python公开数据采集实战:如何解决请求高频拦截与Session会话中断问题
开发语言·python