小编典典

发送表单数组到Flask

flask

我有一个HTML表单,其中包含多个像这样命名的输入:

<input name="hello[]" type="text" />
<input name="hello[]" type="text" />
<input name="hello[]" type="text" />

在PHP中,你可以将其作为数组获取,但是在Python中,使用Flask的方式是否相同?

我已经试过了:

hello = request.form['hello']

print(hello)

但这没有用,我得到了400 Bad Request:

Bad Request

The browser (or proxy) sent a request that this server could not understand.

如何在Flask中进行操作?


阅读 510

收藏
2020-04-05

共1个答案

小编典典

你遵循的PHP约定是在字段名称中添加方括号。它不是Web标准,但是因为PHP开箱即用,因此很流行。Ruby on Rails也使用它。

如果确实使用该约定,则要在Flask一侧获取POST数据,你需要在字段名称中包括方括号。你可以使用来检索列表的所有值MultiDict.getlist()

hello = request.form.getlist('hello[]')

当然,你根本不必使用[]约定。[]hello名称中不附加可以很好地工作,这时你将request.form.getlist('hello')在Flask中使用该名称。

2020-04-05