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/
相关推荐
ID_180079054733 分钟前
Python 采集转转二手商品详情:API 接口与爬虫实战全方案(2026 最新)
开发语言·爬虫·python
斌糖雪梨11 分钟前
spring registerBeanPostProcessors(beanFactory) 源码详解
java·后端·spring
m0_7471245315 分钟前
LangChain 索引增强对话链详解
python·ai·langchain
智算菩萨16 分钟前
【Pygame】第19章 网络多人游戏基础与局域网联机原理
网络·python·游戏·pygame
MarsBighead24 分钟前
VSCode Python 调试故障排查:`justMyCode` 配置项引发的血案
ide·vscode·python
wqww_129 分钟前
springboot 使用websocket来记录移动人物坐标
spring boot·后端·websocket
迷藏49433 分钟前
**发散创新:基于Python与深度学习的情绪识别实战全流程解析**在人工智能快速发展的今天,**情绪识别(Emoti
java·人工智能·python·深度学习
一只幸运猫.35 分钟前
Rust实用工具特型-Clone
开发语言·后端·rust
羊小猪~~43 分钟前
LLM--SFT简介
python·考研·算法·ai·大模型·llm·微调
0xDevNull1 小时前
Java BigDecimal 完全指南:从入门到精通
java·开发语言·后端