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

1 Answer 1

10

There are two ways to do this:

  1. Simply use the 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. Register your own custom route converter (see Werkzeug's documentation for the full details):

    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
    

    which you can then use like this:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.