首页 > 代码库 > flask url转换器,添加另类的url
flask url转换器,添加另类的url
import urllibfrom flask import Flaskfrom werkzeug.routing import BaseConverterapp = Flask(__name__)class ListConverter(BaseConverter): def __init__(self, url_map, separator="+"): super(ListConverter, self).__init__(url_map) self.separator = urllib.unquote(separator) def to_python(self, value): return value.split(self.separator) def to_url(self, values): return self.separator.join(BaseConverter.to_url(value) for value in values)‘‘‘app.url_map.converters{‘default‘: <class ‘werkzeug.routing.UnicodeConverter‘>, ‘string‘: <class ‘werkzeug.routing.UnicodeConverter‘>, ‘int‘: <class ‘werkzeug.routing.IntegerConverter‘>, ‘path‘: <class ‘werkzeug.routing.PathConverter‘>, ‘float‘: <class ‘werkzeug.routing.FloatConverter‘>, ‘any‘: <class ‘werkzeug.routing.AnyConverter‘>, ‘uuid‘: <class ‘werkzeug.routing.UUIDConverter‘>}‘‘‘app.url_map.converters[‘list‘] = ListConverter@app.route(‘/list1/<list:page_names>/‘)def list1(page_names): return ‘Separator: {} {}‘.format("+", page_names)@app.route(‘/list2/<list(separator=u"|"):page_names>/‘)def list2(page_names): return ‘Separator: {} {}‘.format("|", page_names)if __name__ == "__main__": app.run()
http://127.0.0.1:5000/list1/a+b/
Separator: + [u‘a‘, u‘b‘]
http://127.0.0.1:5000/list2/a|b/
Separator: | [u‘a‘, u‘b‘]
自定义转换器需要集成BaseConverter,实现to_python和to_url两个方法
to_python:将路径转化为一个Python对象
to_url: 将路径转化为符合URL格式
摘自《Python Web开发实战》
flask url转换器,添加另类的url
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。