如果我发送这样的表格:
<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/