在Flask中将数组作为表单名称处理 [英] Handling array as form name in flask

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

问题描述

如果我发送这样的表格:

If I send a form like this:

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

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

to PHP script it automatically creates an array and I can access variables like this:

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

和:

 $_POST['filters']

可迭代

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

AND this is my question, how can I get same effect in FLASK?

request.form.getlist('filters')

返回[](空列表)

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

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

return right value but this is not the result of which they expect (its not iterable).

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

Should i rebuild my form or use some other method?

推荐答案

您无法使用键访问python数组/列表,如果要使用键访问数据,请存储您的过滤器作为 json 对象,那么您将可以使用键来访问数据.

You cannot access a python array/list using a key, if you want to access your data using a key, store your filters as a json object, then you will be able to access the data by using a 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中,数组是几件事情.

In php an array is several things.

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中,数组仅 列表通过索引访问.

While in python an array is only a list accessed by index.

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

然后通过密钥访问 dict .

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

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

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