Flask匹配url使用正则表达式

flask匹配url使用正则

需求:url=localhost/auth_id/?参数,当auth_id为4位随机数时,导致web服务器反向代理找不到路径,从而对authid进行正则匹配

实现方式:

  • 从wsgi服务类导入转换器基类
    from werkzeug.routing import BaseConverter
  • 自定义正则转换器类继承于转换器类
    def __init__(self, url_map, regex):
        super().__init__(map=url_map)
        self.regex = regex

    def to_python(self, value):
        return int(value)
  • 在app调用时添加这个类到转换器字典中
    app.url_map.converters['re'] = RegexConverter
  • 在编写路由时可以加入正则表达式
    @api_policy.route('/<re("[0-9]{4}"))/, methods=["POST"])
    实现了使用正则匹配url

猜你喜欢

转载自www.cnblogs.com/jmtang/p/12890062.html
今日推荐