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/
相关推荐
Victor3561 小时前
Redis(158)Redis的主从同步问题如何解决?
后端
Victor3561 小时前
Redis(159)Redis的集群问题如何解决?
后端
少废话h3 小时前
解决Flink中ApacheCommonsCLI版本冲突
开发语言·python·pycharm
serve the people3 小时前
TensorFlow 图执行(tf.function)的 “非严格执行(Non-strict Execution)” 特性
人工智能·python·tensorflow
天命码喽c3 小时前
GraphRAG-2.7.0整合Milvus-2.5.1
开发语言·python·milvus·graphrag
后端小张3 小时前
【JAVA进阶】Spring Boot 核心知识点之自动配置:原理与实战
java·开发语言·spring boot·后端·spring·spring cloud·自动配置
吴佳浩5 小时前
LangChain 深入
人工智能·python·langchain
网安-轩逸8 小时前
回归测试原则:确保软件质量的基石
自动化测试·软件测试·python
X***C8628 小时前
SpringBoot:几种常用的接口日期格式化方法
java·spring boot·后端
Mr_Xuhhh8 小时前
YAML相关
开发语言·python