美文网首页FLASK入门
Flask 路由执行顺序

Flask 路由执行顺序

作者: 大白杏仁 | 来源:发表于2018-01-24 23:42 被阅读89次

    GitHub 文章链接

    Flask 中,当服务器接收到请求后需要进行路由分发,从而能执行不同视图函数。但是当一个 py 文件中出现以下代码,究竟谁执行哪个函数?

    @app.route("/test")
    def test():
        ...
    @app.route("/<to>")
    def page(to):
        ...
    

    不管这两个函数写的顺序如何,当请求 /test 路径时只会进入路由为 @app.route("/test") 的函数中。

    众所周知, Flask 利用 Werkzeug 处理路由分发,它根据路由中有多少变量来决定路由顺序。/test 中没有变量,/<to> 中有一个变量,所以每次路由都会进入 /test。其实排序是根据 Rule.match_compare_key() 方法,看官方文档注释:

    def match_compare_key(self):
        """The match compare key for sorting.
    
        Current implementation:
    
        1.  rules without any arguments come first for performance
            reasons only as we expect them to match faster and some
            common ones usually don't have any arguments (index pages etc.)
        2.  The more complex rules come first so the second argument is the
            negative length of the number of weights.
        3.  lastly we order by the actual weights.
    
        :internal:
        """
    

    为了获得更高的性能,让路径匹配得更快,优先匹配路由中变量较少的,接着根据权重。另外,静态路径权重 > 动态路径权重,同样地会先匹配更短的路径;转换器 converter 也会影响权重,权重从高到低为:数字转换器 -> 基于字符串的转换器 -> 其他转换器。

    ❄️❄️❄️❄️❄️❄️下雪啦❄️❄️❄️❄️❄️❄️

    相关文章

      网友评论

        本文标题:Flask 路由执行顺序

        本文链接:https://www.haomeiwen.com/subject/oxbsaxtx.html