Get multiple request params of the same name

PythonFlask

Python Problem Overview


My problem is that with the given code:

from flask import Flask, request

app = Flask(__name__)

@app.route("/")
def hello():
    return str(request.values.get("param", "None"))

app.run(debug=True)

and I visit:

http://localhost:5000/?param=a&param=bbb

I should expect an output of ['a', 'bbb'] except Flask seems to only accept the first param and ignore the rest.

Is this a limitation of Flask? Or is it by design?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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')

Solution 3 - Python

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)

Solution 4 - Python

> One more way is that you can use one key and one value that holds multiple values and then in the server you can split and do what ever you want .Hope this Helps somewone

http://localhost/api/products/filters?Manufacturer=Dell|HP|HUAWEI|Lenovo
OR
http://localhost/api/products/filters?Manufacturer=Dell_HP_HUAWEI_Lenovo
OR
http://localhost/api/products/filters?Manufacturer=Dell__HP__HUAWEI__Lenovo

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn JiangView Question on Stackoverflow
Solution 1 - PythonBlenderView Answer on Stackoverflow
Solution 2 - PythonVinView Answer on Stackoverflow
Solution 3 - PythonNebulasticView Answer on Stackoverflow
Solution 4 - Pythonuser7956520View Answer on Stackoverflow