标签:div imp 使用 正则表达 导入 转换器 需要 return oat
1 # 路由传递的参数默认当做string处理 2 # 这里指定int,尖括号中冒号后面的内容是动态的 3 4 @app.route(‘/user/<int:id>‘) 5 def hello_itcast(id): 6 return ‘hello itcast {}‘.format(id)
1 # 导入BasseConverter类,作为所有自定义转换器的父类 2 from werkzeug.routing import BaseConverter 3 4 5 # 定义自己的转换器,继承于BaseConvert类 6 class RegexConverter(BaseConverter): 7 def __init__(self, url_map, regex): 8 # 调用父类的构造方法 9 super().__init__(map=url_map) 10 # 将正则表达式的参数保存到对象的属性中,flask会去使用这个属性来进行路由的正则匹配 11 self.regex = regex 12 13 # 将自定义的转换器添加到flask的应用中 14 app.url_map.converters[‘re‘] = RegexConverter 15 16 # 然后就可以用了 re(r‘regex‘):mobile 的方式使用,如下 17 # 这里匹配的是一个十一位的数字 18 @app.route(‘/send/<re(r"\d{11}"):mobile>‘) 19 def send_message(mobile): 20 return ‘send message to {}‘.format(mobile)
通过上述方法,Flask的路由传递参数也可以像Django框架那样灵活的使用正则表达式了
标签:div imp 使用 正则表达 导入 转换器 需要 return oat
原文地址:https://www.cnblogs.com/springionic/p/10792124.html