Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: URLs w/ Variable parameters

Tags:

python

flask

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

like image 683
Paul Avatar asked Sep 03 '13 22:09

Paul


People also ask

How do you pass parameters in a URL in Flask?

In the first one we would use request. args. get('<argument name>') where request is the instance of the class request imported from Flask. Args is the module under which the module GET is present which will enable the retrieve of the parameters.

How do I add a variable to a Flask URL?

To build a URL to a specific function, use the url_for() function. It accepts the name of the function as its first argument and any number of keyword arguments, each corresponding to a variable part of the URL rule. Unknown variable parts are appended to the URL as query parameters.

What is request args in Flask?

request.args is a MultiDict with the parsed contents of the query string. From the documentation of get method: get(key, default=None, type=None) Return the default value if the requested data doesn't exist.

What is App Flask (__ name __)?

app = Flask(__name__, instance_relative_config=True) creates the Flask instance. __name__ is the name of the current Python module. The app needs to know where it's located to set up some paths, and __name__ is a convenient way to tell it that.


1 Answers

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
    
like image 70
Sean Vieira Avatar answered Sep 21 '22 13:09

Sean Vieira