• flask框架(六): 实现支持正则的路由


    一:默认路由

    @app.route('/user/<username>')
    @app.route('/post/<int:post_id>')
    @app.route('/post/<float:post_id>')
    @app.route('/post/<path:path>')
    @app.route('/login', methods=['GET', 'POST'])
    常用路由系统有以上五种,所有的路由系统都是基于一下对应关系来处理:
    
    DEFAULT_CONVERTERS = {
        'default':          UnicodeConverter,
        'string':           UnicodeConverter,
        'any':              AnyConverter,
        'path':             PathConverter,
        'int':              IntegerConverter,
        'float':            FloatConverter,
        'uuid':             UUIDConverter,
    }

    二:写转换器类,支持正则路由

    class RegexConverter(BaseConverter):
        """
        自定义URL匹配正则表达式
        """
    
        def __init__(self, map, regex):
            super(RegexConverter, self).__init__(map)
            self.regex = regex
    
        def to_python(self, value):
            """
            路由匹配时,匹配成功后传递给视图函数中参数的值
            :param value: 
            :return: 
            """
            return value
    
        def to_url(self, value):
            """
            使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数
            :param value: 
            :return: 
            """
            val = super(RegexConverter, self).to_url(value)
            return val
    
    # 添加到flask中
    app.url_map.converters['regex'] = RegexConverter
    
    
    @app.route('/index/<regex("d+"):nid>')  # 使用正则匹配
    def index(nid):
        print(url_for('index', nid='888'))
        return 'Index'
  • 相关阅读:
    for xml path(''),root('')
    [小明带你玩儿Photon]4.一起来看日志
    [小明带你玩儿Photon]3.Hello World i
    [小明带你玩儿Photon]2.从零开始一个程序
    [小明带你玩儿Photon]1.Photon介绍
    杂记
    FluentNHibernate初探[1]
    [Navigation]Navigation初探[2]
    [Navigation]Navigation初探[1]
    动画系统的animator
  • 原文地址:https://www.cnblogs.com/felixwang2/p/9262464.html
Copyright © 2020-2023  润新知