dictionary - WTForms- flask : organize formfield name and data into dictionary

标签 dictionary for-loop flask flask-wtforms wtforms

我已经被困在这个问题上有一段时间了:

我有一个像这样的表格:

class attributes(Form):
    height=IntegerField('height')
    weight=IntegerField('weight')

class main(Form):
    John=FormField(attributes)
    Ted=FormField(attributes)
    David(FormField(attributes)`

我希望迭代创建一个字典来在 flask 中存储标识字段标签和字段数据,而不为每个 FormField 使用 John_height=John.height.data 。这个想法是最终使用 SQL 语句传递字典以写入数据库,其中字典键将与数据库列匹配,表单字段数据将是数据库值。

字典应该看起来像这样:

{John_height : 170,
John_weight: 170,
Ted_height : 120,
Ted_weight: 190,
David_height : 150,
David_weight: 100}

提前谢谢您。

最佳答案

from wtforms import Form
from wtforms.fields import IntegerField, FormField

class Attributes(Form):
    height = IntegerField('height')
    weight = IntegerField('weight')

要迭代构建表单,您可以执行以下任一操作:

def main(people=['John', 'Ted', 'David']):
    class Main(Form):
        pass
    for person in people:
        setattr(Main, person, FormField(Attributes))
    return Main()

class Main(Form):
    for person in ['John', 'Ted', 'David']:
        vars()[person] = FormField(Attributes)
    del person

我个人更喜欢第二种,因为它是一个适当的类结构,但动态性较差。

要构建字典,您可以执行以下操作:

obj = Main()

data = dict()
for field in obj:  # <- this works since obj has an __iter__ method self defined
    for key in field.data.keys():
        data.update({field.name + '_' + key: field.data[key]})

print(data)
>>> {'John_height': None, 'John_weight': None, 'Ted_height': None, 'Ted_weight': None, 'David_height': None, 'David_weight': None}

None 值是由于空表单构造造成的。

关于dictionary - WTForms- flask : organize formfield name and data into dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52635146/

相关文章:

python - 使用键作为列标题将 python 字典写入 CSV 文件

javascript - 从 json 文件中提取包含数组中值的项目

PHP 会更改循环的范围并在包含的文件中进行切换

java - 具有指数条件的大 O/时间复杂度

arrays - 奇怪的golang“append ”行为(覆盖 slice 中的值)

python - 在应用程序上下文之外获取配置变量

java - 从具有 <String, Class> 属性 HashMaps 的 bean 注入(inject)类

python - 使用 Oauth2 在 Flask 中使用特定托管域 (hd) 对用户进行身份验证

python - 仅在 Flask 应用程序中显示未分类的消息

json - 使用ansible映射从json获取值