你的安全设置不允许网站,wordpress 用微信登陆,wordpress做社区 商城,云开发步骤 创建自定义转换器类 继承 werkzeug.routing.BaseConverter。实现 to_python 和#xff08;可选#xff09;to_url 方法。 将转换器注册到 Flask 应用 在路由中使用转换器 示例 创建转换器
假设需要自定义一个转换器 FourDigitYearConverter#xff0c;用于匹配四位年… 步骤 创建自定义转换器类 继承 werkzeug.routing.BaseConverter。实现 to_python 和可选to_url 方法。 将转换器注册到 Flask 应用 在路由中使用转换器 示例 创建转换器
假设需要自定义一个转换器 FourDigitYearConverter用于匹配四位年份。
# converters.pyfrom werkzeug.routing import BaseConverterclass 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 应用中注册转换器
from flask import Flask
from converters import FourDigitYearConverterapp Flask(__name__)# 注册转换器
app.url_map.converters[yyyy] FourDigitYearConverter定义路由
app.route(/year/yyyy:year/)
def year_view(year):return fThe year is {year}.测试路由
访问 /year/2024/ 时
URL 参数 2024 被捕获并转换为整数 2024。
反向生成 URL
with app.test_request_context():url flask.url_for(year_view, year2024)print(url) # 输出/year/2024/