Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get multiple request params of the same name

Tags:

python

flask

People also ask

How do I pass multiple parameters in GET request URL?

Any word after the question mark (?) in a URL is considered to be a parameter which can hold values. The value for the corresponding parameter is given after the symbol "equals" (=). Multiple parameters can be passed through the URL by separating them with multiple "&".

How can I get multiple parameters with same name from URL in PHP?

For GET requests you can parse $_SERVER['QUERY_STRING'] yourself and for non- enctype="multipart/form-data" POST requests you can parse file_get_contents("php://input") .


You can use getlist, which is similar to Django's getList but for some reason isn't mentioned in the Flask documentation:

return str(request.args.getlist('param'))

The result is:

[u'a', u'bbb']

Use request.args if the param is in the query string (as in the question), request.form if the values come from multiple form inputs with the same name. request.values combines both, but should normally be avoided for the more specific collection.


If you used $('form').serialize() in jQuery to encode your form data, you can use request.form['name'] to get data, but note that when multiple input elements' names are the same, request.form['name'] will only get the first matched item. So I checked the form object from the Flask API, and I found this. Then I checked the MultiDict object, and I found the function getlist('name').

If there are multiple inputs with the same name, try this method: request.form.getlist('name')


Another option is to use a flat json structure with request.args. Because sometimes you simply do not know the parameter beforehand and you cannot use .getlist().

arguments = request.args.to_dict(flat=False)

# Get a specific parameter
param = arguments.get('param')
print(param)

# Get all the parameters that have more than one value
for field, values in arguments.items():
    if len(values) > 1:
        print(values)