Flask 路由执行顺序

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 也会影响权重,权重从高到低为:数字转换器 -> 基于字符串的转换器 -> 其他转换器。



作者:大白杏仁
链接:https://www.jianshu.com/p/6368b281d866
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值