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
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.
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.
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.
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.
There are two ways to do this:
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With