wtforms接收json类型数据并验证

AttributeError: type object 'WXLoginForm' has no attribute 'from_json'

出现上面问题的百分之九十都是因为没写以下内容:

···

import wtforms_json

wtforms_json.init()

···

使用流程如下:

Quickstart

In order to start using WTForms-JSON, you need to first initialize the extension. This monkey patches some classes and methods within WTForms and adds JSON handling support:

First Example

After the extension has been initialized we can create an ordinary WTForms form. Notice how we are initalizing the form using from_json() class method:

class LocationForm(Form):
    name = TextField()
    address = TextField()

class EventForm(Form):
    name = TextField()
    is_public = BooleanField()

json = {
    'name': 'First Event',
    'location': {'name': 'some location'},
}

form = EventForm.from_json(json) # 此处调用了from_json,即可接收json对象

If you want WTForms-JSON to throw errors when unknown json keys are encountered just pass skip_unknown_keys=False to from_json():

Throws exception

form = EventForm.from_json(json, skip_unknown_keys=False)

最后的生产环境样例:

from flask import request

class EventForm(Form):
    name = TextField()
    is_public = BooleanField()

form = EventForm.from_json(class EventForm(Form):
    name = TextField()
    is_public = BooleanField()


form = EventForm.from_json(request.json)  

我知道有蛋疼的哥们跟我遇到一样的问题,话不多说,喜欢点赞

你可能感兴趣的:(wtforms接收json类型数据并验证)