sanic-org / sanic

Accelerate your web app development | Build fast. Run fast.
https://sanic.dev
MIT License
18k stars 1.54k forks source link

Getting first element of an array in request.form.get('arr_name') #2698

Closed LucasGrasso closed 1 year ago

LucasGrasso commented 1 year ago

I was getting the first element of a array(named 'search_strings'). Passing search_strings = ['V','F','X'] and req.form.get('search_strings') would only retrieve 'V'.

print(req.form) #outputs {'search_strings': ['V', 'F', 'X']}
print(req.form.get("search_strings")) #outputs V

Had to use

json.loads(str(req.form).replace("'", '"'))[
        "search_strings"
    ]

Being passed as: image

Originally posted by @LucasGrasso in https://github.com/sanic-org/sanic/issues/288#issuecomment-1445742071

ahopkins commented 1 year ago

Oy... that's an ugly hack. I would use getlist

The request.form object is one of a few types that is a dictionary with each value being a list. This is because HTTP allows a single key to be reused to send multiple values.

Most of the time you will want to use the .get() method to access the first element and not a list. If you do want a list of all items, you can use .getlist().

source