Flask自定义转换器,实现路由匹配正则表达式参数

Flask框架动态路由实现参数传递和Django框架有类似之处,但是相比于Django框架,Flask实现复杂的参数就需要自己自定义转换器来实现了,而不能向Django那样直接使用正则表达式

1 # 路由传递的参数默认当做string处理
2 # 这里指定int,尖括号中冒号后面的内容是动态的
3 
4 @app.route('/user/<int:id>')
5 def hello_itcast(id):
6     return 'hello itcast {}'.format(id)

Flask默认的转换器有以下几种

  • int::接受整数
  • float:同int,但是接受浮点数
  • path:和默认的相似,但也接受斜线

让Flask向Django一样拥有一个正则表达式匹配参数的功能

 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框架那样灵活的使用正则表达式了

猜你喜欢

转载自www.cnblogs.com/springionic/p/10792124.html