【问题标题】:Are Python flask order of routes defined?是否定义了 Python 烧瓶路线的顺序?
【发布时间】:2014-07-29 09:10:23
【问题描述】:

在我看来,我有一个类似于以下的设置:

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

似乎示例中的函数 test 在访问“/test” url 时总是会被调用。这也是我想要的。但我在文档中找不到这种行为。是不是定义的名称总是优先于变量?还是定义的顺序很重要?我可以以任何方式设置优先级以确保将来不会中断吗?

【问题讨论】:

    标签: python python-2.7 flask


    【解决方案1】:

    Flask 使用Werkzeug 处理路由,它根据路由中有多少可变部分对路由进行排序。

    /test 没有可变部分,而/&lt;to&gt; ,所以它会首先尝试匹配/test

    目前,订购是基于Rule.match_compare_key() function,记录为:

    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:
        """
    

    权重由路径的静态部分(比动态部分权重更大,首先匹配较短的路径)或转换器的特定权重(数字转换器在基于字符串的转换器之前排序,在任意路径转换器)。

    【讨论】:

    • 我在哪里询问重量,但看到你的编辑。很好的答案!
    猜你喜欢
    • 2012-12-11
    • 2012-12-22
    • 2013-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    相关资源
    最近更新 更多