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, }

 
自定义路由系统:
from flask import Flask, views, url_for
from werkzeug.routing import BaseConverter  #所有路由匹配都来自于BaseConverter类

app = Flask(import_name=__name__)


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 int(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(nid, type(nid))
    print(url_for('index', nid=nid))
    return 'index'


if __name__ == '__main__':
    app.run()
posted @ 2020-12-01 23:33  暗夜精灵123  Views(66)  Comments(0Edit  收藏  举报