将表单数组发送到 Flask [英] Sending a form array to Flask

查看:30
本文介绍了将表单数组发送到 Flask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个输入的 HTML 表单,名称如下:

I have an HTML form with multiple inputs named like this:

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

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

In PHP you get this as an array but is it the same way in Python, using Flask?

我已经试过了:

hello = request.form['hello']

print(hello)

但这不起作用,我收到了一个 400 Bad Request:

But that did not work, I got a 400 Bad Request:

Bad Request

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

如何在 Flask 中执行此操作?

How do I do it in Flask?

推荐答案

您正在关注 PHP 为字段名称添加括号的约定.它不是 Web 标准,但由于 PHP 开箱即用地支持它,因此它很受欢迎;Ruby on Rails 也使用它.

You are following a PHP convention of adding brackets to the field names. It's not a web standard, but because PHP supports it out of the box it is popular; Ruby on Rails also uses it.

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

If you do use that convention, to get the POST data on the Flask side you need to include the square brackets in the field name. You can retrieve all values of the list using MultiDict.getlist():

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

当然,您根本不必使用 [] 约定.不将 [] 附加到 hello 名称将工作得很好,此时您将使用 request.form.getlist('hello') 在 Flask 中.

You don't have to use the [] convention at all, of course. Not appending the [] to the hello name will work perfectly fine, at which point you'd use request.form.getlist('hello') in Flask.

这篇关于将表单数组发送到 Flask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆