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/
相关推荐
怒放吧德德7 小时前
Java 网络编程核心:BIO、NIO、AIO IO 模型深度解析与实战
后端·netty
nimadan127 小时前
**AI漫剧软件2025推荐,解锁高性价比创意制作新体验**
人工智能·python
Java后端的Ai之路9 小时前
【JDK】-JDK 21 新特性内容
java·开发语言·后端·jdk·jdk21
yunhuibin10 小时前
GoogLeNet学习
人工智能·python·深度学习·神经网络·学习
易辰君10 小时前
【Python爬虫实战】正则:中文匹配与贪婪非贪婪模式详解
开发语言·爬虫·python
普通网友10 小时前
PHP语言的正则表达式
开发语言·后端·golang
秀儿还能再秀10 小时前
正则表达式核心语法 + Python的 re 库中常用方法
python·正则表达式
xcLeigh10 小时前
Python入门:Python3 正则表达式全面学习教程
python·学习·正则表达式·教程·python3
多恩Stone11 小时前
【C++ debug】在 VS Code 中无 Attach 调试 Python 调用的 C++ 扩展
开发语言·c++·python
葵续浅笑12 小时前
从Spring拦截器到Filter过滤器:一次报文修改加解密的填坑经验
java·后端·spring