Python 将表单数组发送到 Flask

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24808660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:15:16  来源:igfitidea点击:

Sending a form array to Flask

pythonhtmlflask

提问by theva

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

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

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

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

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

I have tried this:

我试过这个:

hello = request.form['hello']

print(hello)

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

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

Bad Request

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

How do I do it in Flask?

我如何在 Flask 中做到这一点?

采纳答案by Martijn Pieters

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.

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

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

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

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

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

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

回答by ahuigo

I written a parse function which supports multidimensional dict:php_post=parse_multi_form(request.form)

我写了一个支持多维字典的解析函数:php_post=parse_multi_form(request.form)

def parse_multi_form(form):
    data = {}
    for url_k in form:
        v = form[url_k]
        ks = []
        while url_k:
            if '[' in url_k:
                k, r = url_k.split('[', 1)
                ks.append(k)
                if r[0] == ']':
                    ks.append('')
                url_k = r.replace(']', '', 1)
            else:
                ks.append(url_k)
                break
        sub_data = data
        for i, k in enumerate(ks):
            if k.isdigit():
                k = int(k)
            if i+1 < len(ks):
                if not isinstance(sub_data, dict):
                    break
                if k in sub_data:
                    sub_data = sub_data[k]
                else:
                    sub_data[k] = {}
                    sub_data = sub_data[k]
            else:
                if isinstance(sub_data, dict):
                    sub_data[k] = v

    return data

Usage:

用法:

>>> request.form={"a[0][name]": "ahui", "a[0][sex]": "female", "a[1][name]": "bhui", "a[1][sex]": "male"}
>>> parse_multi_form(request.form)
{'a': {0: {'name': 'ahui', 'sex': 'female'}, 1: {'name': 'bhui', 'sex': 'male'}}}

Warnning:It does not support list,e.g. a[][0]=1&a[][0]=2, it may make programmer to be confused. Either a=[[1,2]]or a[[1],[2]]is too hard to choose.

警告:它不支持列表,例如a[][0]=1&a[][0]=2,它可能会让程序员感到困惑。无论是a=[[1,2]]a[[1],[2]]太硬的选择。

So I suggest use dict to replace list:

所以我建议使用 dict 来替换列表:

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

If you still want to post complex data, I suggest you use application/json

如果你仍然想发布复杂的数据,我建议你使用 application/json