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/
相关推荐
Asize14 小时前
重生之我在 Vibe Coding 时代当程序员:第十五课,正则表达式和 HTTP 请求:规则不是背出来的,是拆出来的
前端·javascript·后端
惜缘破军14 小时前
基于 Spring Boot 3 和 Spring Cloud 2023 的微服务基础框架 hdfk7-boot
spring boot·后端·微服务
Asize14 小时前
重生之我在 Vibe Coding 时代当程序员:第十六课,从模拟队列到原型链
前端·javascript·后端
砍材农夫14 小时前
python 如何一次性安装项目所有依赖包(pip和uv)
开发语言·python·pip·uv
山水洛行14 小时前
吃透这 17 个概念,比 95% 的开发者更懂 AI
后端
yijianace14 小时前
Python爬虫项目实战:从 BeautifulSoup 到 XPath
爬虫·python·beautifulsoup
云水-禅心14 小时前
解决MacOS 安装Python之后默认版本指向不正确问题
开发语言·python·macos
Csvn14 小时前
Linux 文件与目录操作命令(通关版)
后端
cjp56014 小时前
007. ASP.NET WEB API配置JWT令牌身份认证
后端·asp.net