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)  

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,694评论 0 10
  • 最近很喜欢歌手毛不易,他写的歌词,没有华丽的辞藻,但却是扎心的恰到好处。让我这个平凡人一听就能有共鸣。 初中的时候...
    猫胡说阅读 163评论 0 1

友情链接更多精彩内容