Python Flask 路由顺序有定义吗?
我在我的视图中有一个类似下面的设置:
@app.route("/test")
def test():
...
@app.route("/<to>")
def page(to):
...
看起来在访问“/test”这个网址时,示例中的test函数总是会被调用。这正是我想要的。但是我在文档中找不到这种行为的说明。是说定义的名字总是比变量优先吗?还是说定义的顺序很重要?我能否以某种方式设置优先级,以确保将来不会出问题?
1 个回答
13
Flask使用Werkzeug来处理路由,也就是决定用户请求的地址应该由哪个功能来处理。Flask会根据路由中有多少个可变部分来排列这些路由。
/test
这个路由没有可变部分,而/<to>
这个路由有可变部分,所以Flask会先尝试匹配/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:
"""
权重是根据路径中静态部分和动态部分来决定的,静态部分的权重更高,短的路径会优先匹配。还有就是根据转换器的特定权重来排序,比如数字转换器会排在字符串转换器之前,而字符串转换器又会排在任意路径转换器之前。