简体   繁体   English

Python Flask json 模式验证

[英]Python flask json schema validation

I am using the flask framework in my new project.我在我的新项目中使用了 Flask 框架。 It would get JSON data from the post and send a JSON response.它将从帖子中获取 JSON 数据并发送 JSON 响应。 So, I need to validate my JSON request.所以,我需要验证我的 JSON 请求。 I have seen couple of libraries.我见过几个图书馆。 But those libraries are not working as expected.但是这些库没有按预期工作。 Finally, I have decided to go with a flask-jsonschema-validator.最后,我决定使用flask-jsonschema-validator。 It is working fine with a single JSON object.它适用于单个 JSON 对象。 If the request object has a nested object, it is not working.如果请求对象具有嵌套对象,则它不起作用。 For example,例如,

from flask_jsonschema_validator import JSONSchemaValidator
JSONSchemaValidator(app=app, root="schemas")

This is my initialization of the validator.这是我对验证器的初始化。

# If any error occurred in the request.
@app.errorhandler(jsonschema.ValidationError)
def json_validation_error(e):
    return json_response("error", str(e), {})

This is my error handler这是我的错误处理程序

@app.validate('model', 'save') def save_model(): @app.validate('model', 'save') def save_model():

This is my implementation.这是我的实现。

{
  "save": {
    "type": "object",
    "properties": {
      "workspace": {"type": "object"},
      "name": {"type": "string"},
      "description": {"type": "string"},
      "uri": {"type": "string"},
      "type": {
         "name": {"type": "string"},
      }
    },
    "required": [ "workspace", "name", "description", "uri", "type"]
  }
}

This is my model.json file.这是我的 model.json 文件。 It is validating the request except for the "type".它正在验证除“类型”之外的请求。 How to apply validation for JSON request with nested object如何使用嵌套对象对 JSON 请求应用验证

Please help anyone to fix this problem请帮助任何人解决这个问题

Thanks in advance.提前致谢。

flask-expects-json package checks variables types on nested objects. flask-expects-json包检查嵌套对象上的变量类型。

It work as a decorator on your route.它可以作为您路线上的装饰器。

SCHEMA = {
    "type": "object",
    "properties": {
      "workspace": {"type": "object"},
      "name": {"type": "string"},
      "description": {"type": "string"},
      "uri": {"type": "string"},
      "type": {
         "type": "object",
         "properties": {
              "name": {"type": "string"},
         }
      }
    },
    "required": ["workspace", "name", "description", "uri", "type"]
}

@expects_json(SCHEMA)
def my_route(self, **kwargs):
    pass

If the validation of complex nested objects, I would recommend an alternative tool to JSONSchema.如果验证复杂的嵌套对象,我会推荐 JSONSchema 的替代工具。 I can replicate your schema validation in GoodJSON like below.我可以在GoodJSON 中复制您的架构验证,如下所示。 As you can see, formulating a validation schema is just composing a bunch of self-contained validator functions that can be applied to objects, lists and primitive values.如您所见,制定验证模式只是组合了一堆可应用于对象、列表和原始值的自包含验证器函数。

from goodjson.validators import is_dict, is_string, is_uri, foreach_key


validate_fun = foreach_key(
    save=[foreach_key(
        workspace=[is_dict],
        name=[is_string],
        description=[is_string],
        uri=[is_uri],
        type=[foreach_key(
            name=[is_string]
        )]
    )]
)

validate_fun(YOUR_JSON_DATA_OBJECT)

Disclaimer: I am the author of GoodJSON.免责声明:我是 GoodJSON 的作者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM