6

I have a URL string I want to build in the following manner:

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

How would I generate something like this in my URL mapping where n is a variable number?

How would I get those keys?

Thanks

4

1 回答 1

10

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

  1. 只需使用path路由转换器

    @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. 注册您自己的自定义路由转换器(有关详细信息,请参阅Werkzeug 的文档):

    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
    
于 2013-09-04T04:05:32.863 回答