标签:添加 开发 sel 转换 values lis int urllib flask
import urllib from flask import Flask from werkzeug.routing import BaseConverter app = 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开发实战》
标签:添加 开发 sel 转换 values lis int urllib flask
原文地址:http://www.cnblogs.com/jachin/p/6444699.html