【问题标题】:efficiently writing WTForm submission to mysql高效地将 WTForm 提交写入 mysql
【发布时间】:2018-09-20 14:37:43
【问题描述】:

我的 wtform 很长:

Question1 = TextAreaField('What is your name?')
...
Question100=TextAreaField('Describe your role')

当用户提交表单时,Flask 会检索每个问题的数据:

Question1=form.Question1.data
..
Question100=form.Question100.data

然后我使用 sql 将数据写入数据库 即

cursor.executve("INSERT INTO table (Q1,Q100) values (%s,%s)", (Question1, Question100))

SQL 注入不是问题,我不想使用 SQLalchemy。有没有更有效的方法来做到这一点?

编辑: 假设某些字段类型是 FieldLists、Formfields 或 HiddenFields。我怎么能把这些写到表里?如何循环跳过它们?

【问题讨论】:

    标签: mysql flask flask-wtforms


    【解决方案1】:

    快速且易读的解决方案

    written_fields = [f for f in form if f.id in WRITE_TO_SQL_FIELDS]
    cursor.execute(
        "INSERT INTO table ({}) values ({})".format(
            ",".join(f.id for f in written_fields),
            ",".join(str(f.data) for f in written_fields),
        )
    )
    

    或者,如果您更喜欢按类型过滤:

    BLACKLISTED_TYPES = (wtforms.FieldList, wtforms.Formfield, wtforms.HiddenField)
    written_fields = [f for f in form if not isinstance(f, BLACKLISTED_TYPES)] 
    

    【讨论】:

    • 嗨 Fian,感谢您的解决方案。回想起来,我本来可以更详细地了解最初的帖子。你能告诉我在循环/写入 SQL 时如何解释或排除 FieldlistsFormFieldsHiddenFields
    • 更改了我的答案以支持字段排除。至少有两种方法:通过应写入数据库的字段名称列表,或者您可以按类型过滤字段(我不喜欢这种方法)。
    猜你喜欢
    • 1970-01-01
    • 2016-12-30
    • 2019-11-14
    • 2016-04-14
    • 2023-04-02
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多