【问题标题】:request json validation in the flask在烧瓶中请求 json 验证
【发布时间】:2016-03-09 18:38:03
【问题描述】:

是否有一些最佳实践如何在 Flask 中验证 json 请求? Flask restful 扩展中有一种有趣的方法,但我的应用程序中不需要它。 我只想拥有这样的东西:

user_schema = {
    'username': email,
    'password': required,
    'age': required
}


@app.route('new_user/', methods=['POST'])
def new_user():
    validate_json(request.json, user_schema)

【问题讨论】:

  • 可能值得一看 WTForms-JSON 或类似的。
  • 您要验证什么? Marshmallow 非常适合序列化和验证。
  • 我正在尝试验证来自客户端的 JSON。我需要验证这个 JSON 中的字段。
  • 你应该像@PatrickAllen 提到的那样使用棉花糖。我在一个项目中使用了 webargs (webargs.readthedocs.org/en/latest),该项目有点建立在 marschmallow 之上,或者更确切地说是使用它的验证器。如果您正在构建某种 rest api,您可以尝试一下。
  • 非常感谢:@PatrickAllen 和 minato。我会看看他们两个。

标签: json validation flask


【解决方案1】:

看看cerberus

示例用法:

>>> from cerberus import Validator
>>> schema = {'name': {'type': 'string', 'required': True}}
>>> v = Validator(schema)
>>> document = {'bla': 'john doe'}
>>> v.validate(document)
False
>>>

【讨论】:

    猜你喜欢
    • 2014-07-23
    • 2016-05-03
    • 2016-04-21
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 2018-08-22
    相关资源
    最近更新 更多