【问题标题】:How to store WTForm Form in session in Flask?如何在 Flask 的会话中存储 WTForm 表单?
【发布时间】:2015-11-20 02:56:23
【问题描述】:

我需要在会话中存储表单的结果,但我不断收到 TypeError: XXX is not JSON serializable for datetimes 和 Decimal 字段。在请求之间保留表单数据的正确方法是什么?

这是我的表格:

class GiftRequestForm(Form):
    giftee_name = StringField('Name',
                          [validators.Required(), validators.length(min=4, max=25)])
    giftee_age = IntegerField('Age',
                          [validators.Required(),
                           validators.NumberRange(min=0, message="Age must be greater than 0")])
    giftee_sex = RadioField('Gender',
                        [validators.Required()],
                        choices=[('0', 'Male'), ('1', 'Female')])
    giftee_relationship = StringField('Relationship',
                                  [validators.Required(), validators.length(min=4, max=25)],
                                  description='Fill in the blank: The recipient is my _____.')
    event = StringField('Event',
                    [validators.Required(), validators.length(min=4, max=80)])
    event_date = DateField('Event Date',
                       [validators.Required()],
                       format='%Y-%m-%d',
                       description="Well have it to you at least four days before the event date.")
    budget = DecimalField('Budget $',
                      [validators.Required(),
                       validators.NumberRange(min=0, message="Budget must be greater than 0")])

在我看来,我只想做:

form = GiftRequestForm()
...
session['gift_request_form'] = form

这根本不起作用,因为 GiftRequestForm 似乎不是 JSON 可序列化的。不幸的是,这也不起作用:

session['gift_request_form'] = form.data

因为我的字典中的一个元素是日期时间和十进制类型。所以我总是得到一个 TypeError: datetime.date(2015, 9, 2) is not JSON serializable,或者 Decimal 字段的类似内容。

这似乎是一种标准模式——但我很难让它发挥作用。我该怎么做?

【问题讨论】:

  • date 类型不是 JSON 可序列化的,您可以改用时间戳。

标签: serialization flask flask-wtforms


【解决方案1】:

您可以将日期和小数转换为字符串,然后再将其存储到会话中。然后使用strptime 将会话中的字符串中的日期时间转换回您需要访问它的日期,并使用Decimal 转换十进制值。不得不为会话组装字典并将这些值重新转换为字符串,这对我来说感觉像是一个杂物,但是由于序列化的限制,我不知道更好的方法。

【讨论】:

    猜你喜欢
    • 2017-12-22
    • 1970-01-01
    • 2014-01-17
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 2016-09-01
    • 2019-03-11
    相关资源
    最近更新 更多