如果我发送这样的表单:
<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 数组/列表,如果您想使用键访问您的数据,请将您的 filters 存储为 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'
