flask自定义转化器实现正则匹配

自定义转化器

#非重点
#1 写类,继承BaseConverter
#2 注册:app.url_map.converters['regex'] = RegexConverter  # 这个类自己定义
# 3 使用:@app.route('/index/<regex("d+"):nid>')  正则表达式会当作第二个参数传递到类中

from flask import Flask, url_for
from werkzeug.routing import BaseConverter

app = Flask(import_name=__name__)

class RegexConverter(BaseConverter):  # 类名无所谓可以自己定义
    """
    自定义URL匹配正则表达式
    """
    def __init__(self, map, regex):
        super(RegexConverter, self).__init__(map)
        self.regex = regex  # 添加属性

    def to_python(self, value):  # to_paython的作用就是对匹配成功的结果进行处理然后传递给响应函数的形参nid
        """
        路由匹配时,匹配成功后传递给视图函数中参数的值
        """
        print("to_python",value,type(value))
        return int(value)+1  # 可对结果进行再处理,这里将前端传递过来的str变成int

    def to_url(self, value):  # 可对反向解析时对路由传递的参数进行处理
        """
        使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数
        """
        val = super(RegexConverter, self).to_url(value)
        return val+"222"

# 添加到flask中
app.url_map.converters['regex'] = RegexConverter
# 正则匹配处理结果,要交给to_python,to_python函数可以对匹配处理结果做处理
@app.route('/index/<regex("d+"):nid>')
def index(nid):
    print("index",nid,type(nid))
    print(url_for('index', nid='888'))
    return 'Index'

if __name__ == '__main__':
    app.run()

总结(步骤):

1 导入from werkzeug.routing import BaseConverter
2 我写个继承BaseConverter。实现3个方法,def __init__ , def to_python , def to_url
3 将上面的类注册到app.url_map.converters['regex'] = RegexConverter中
4 然后就可以在路由转化器中使用3中的regex("传正则")
5 当路由被访问以后。regex("传正则")会匹配结果,把结果传递to_python,我们可以进行再次处理,to_python处理好的结果,会传递给响应函数的形参
6 当用url做反向解析的时候,传递给路由转化器的参数,会经过to_url,进行处理。处理以后,在拼接到路由。
原文地址:https://www.cnblogs.com/yafeng666/p/12521275.html