Flask:带有可变参数的URL

时间:2013-09-03 22:08:05

标签: python flask

我想用以下方式构建一个URL字符串:

http://something.com/mainsite/key1/key2/key3/keyn

如何在我的URL映射中生成这样的内容,其中n是变量号?

我如何获得这些钥匙?

由于

1 个答案:

答案 0 :(得分:7)

有两种方法可以做到这一点:

  1. 只需使用path route converter

    @app.route("/mainsite/<path:varargs>")
    def api(varargs=None):
        # for mainsite/key1/key2/key3/keyn
        # `varargs` is a string contain the above
        varargs = varargs.split("/")
        # And now it is a list of strings
    
  2. 注册您自己的custom route converter(有关完整详情,请参阅Werkzeug's documentation):

    from werkzeug.routing import BaseConverter, ValidationError
    
    class PathVarArgsConverter(BaseConverter):
        """Convert the remaining path segments to a list"""
    
        def __init__(self, url_map):
            super(PathVarArgsConverter, self).__init__(url_map)
            self.regex = "(?:.*)"
    
        def to_python(self, value):
            return value.split(u"/")
    
        def to_url(self, value):
            return u"/".join(value)
    
    app.url_map.converters['varargs'] = PathVarArgsConverter
    

    然后您可以像这样使用:

    @app.route("/mainsite/<varargs:args>")
    def api(args):
        # args here is the list of path segments