python - 在 Flask 中将数组处理为表单名称

标签 python flask

如果我发送这样的表格:

<form method="POST" ...>
    <input type="text" name="filters[price_from]">
    <input type="text" name="filters[price_to]">
</form>

对于 PHP 脚本,它会自动创建一个数组,我可以访问如下变量:

$_POST['filters']['price_to']

和:

 $_POST['filters']

可迭代

这是我的问题,如何在 FLASK 中获得相同的效果?

request.form.getlist('filters')

返回[](空列表)

request.form.get('filters[price_from]')

返回正确的值,但这不是他们期望的结果(它不可迭代)。

我应该重建我的表单还是使用其他方法?

最佳答案

您无法使用键访问Python数组/列表,如果您想使用键访问数据,请将您的过滤器存储为json对象,然后您将能够使用 key 访问数据。

<form method="POST" enctype="application/JSON">
    <input type="text" name="filters[price_from]" value="" >
    <input type="text" name="filters[price_to]" value="" >
</form>

filters = request.get_json()

filters['price_from'] #returns price_from value
filters['price_to'] #returns price_to value

在 php 中,数组有多种含义。

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.

而在 python 中,数组只是 list通过索引访问。

>>> filters = ['price_from', 'price_to']
>>> filters[0]
'price_from'
>>> filters[1]
'price_to'

还有一个dict通过 key 访问。

>>> filters = {'price_from':'value', 'price_to':'another_value'}
>>> filters['price_from']
'value'
>>> filters['price_to']
'another_value'

关于python - 在 Flask 中将数组处理为表单名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38126371/

相关文章:

python - uWSGI + flask +自己的多进程?

linux - 简单的基本 Flask 应用程序中的权限错误权限被拒绝

python - tkinter,如何跨按钮拖动?

python - "are"类的类属性/属性的正确 python 命名约定?

对所有捕获的异常执行常见操作的 Pythonic 方式

python - Flask - 将变量从 URL 传递给函数

python - Flask Python 刚刚开始向 url 添加随机哈希 .dpbs

python - Flask 运行 request.method 默认为 'POST' 而不是 'GET'

javascript - Python 2.7x 中是否有像 Javascript 中那样的对象传播语法?

python - keras 层在每个 epoch 重新启动一部分权重