python marshmallow:验证嵌套请求的任何解决方法 JSON?

python marshmallow: any workaround to validate nested request JSON?

我想用 marshmallow 验证嵌套请求 JSON,我几乎按照它的文档来验证我的请求 JSON 数据。经过多次尝试,我认为使用 marshmallow 来验证复杂的 JSON 数据是正确的方法。但是,我从 marshmallow 收到如下验证错误:

已更新错误消息

> PS C:\Users\jyson\immunomatch_api> python .\json_validation.py
> Traceback (most recent call last):   File ".\json_validation.py", line
> 58, in <module>
>     app = schema.load(app_data)   File "C:\Users\jyson\AppData\Local\Programs\Python\Python37\lib\site-packages\marshmallow\schema.py",
> line 723, in load  
>     data, many=many, partial=partial, unknown=unknown, postprocess=True   File
> "C:\Users\jyson\AppData\Local\Programs\Python\Python37\lib\site-packages\marshmallow\schema.py",
> line 904, in _do_load
>     raise exc marshmallow.exceptions.ValidationError: {'_schema': ['Invalid input type.']}

更新

在我得到位置参数错误之前,因为我隐式定义了像 def __init__(self, age, gender, features) 这样的特征,而不是在 def init(self, age, gender, IL10, CRP ).为什么我有上述错误?任何快速的想法?谢谢

我尝试用棉花糖json验证:

from marshmallow import Schema, fields, post_load
from marshmallow import EXCLUDE
import json

class Feature(object):
    def __init__(self, value, device):
        self.value = value
        self.device= device

class FeatureSchema(Schema):
    value = fields.Str()
    device= fields.Str()

    @post_load
    def make_feature(self, data, **kwargs):
        return Feature(**data)

class App(object):
    def __init__(self, age, gender, features):
        self.age = age
        self.gender = gender
        self.features = features

class AppSchema(Schema):
    age = fields.Str()
    gender = fields.Str()
    features = fields.Nested(FeatureSchema)

    @post_load
    def make_app(self, data, **kwargs):
        return App(**data)

json_data = """{

"body": {
    "gender": "M",
    "PCT4": {
      "value": 12,
      "device": "roche_cobas"
    },
    "IL10": {
      "value": 12,
      "device": "roche_cobas"
    },
    "CRP": {
      "value": 12,
      "device": "roche_cobas"
    },
     "OM10": {
      "value": 120,
      "device": "roche_bathes"
    }
  }
}"""

app_data = json.loads(json_data)

schema = AppSchema(unknown=EXCLUDE, many=TRUE)
app = schema.load(app_data)

print(app.data.features.value)

为什么会出现以上错误?验证嵌套 JSON 的正确方法是什么?为什么我有未知的字段错误?任何可能的想法来摆脱上面的错误?谢谢

错误清楚地提到了问题

marshmallow.exceptions.ValidationError: {'OM10': ['Unknown field.'], 'CRP': ['Unknown field.'], 'IL10': ['Unknown field.'], 'PCT4': ['Unknown field.']}

Marshmallow 的架构不理解该字段,因为您尚未将其声明到您的架构中,默认情况下,如果 Marshmallow 发现 Unknown Field

将引发错误

一个简单的解决方法是 EXCLUDE 他们在查看您的代码时,似乎您根本不​​需要它。

我建议在实例化时将 unknown 参数作为 EXCLUDE 传递。

from marshmallow import EXCLUDE
schema = AppSchema(unknown=EXCLUDE)

可以在此处找到更多信息 - https://marshmallow.readthedocs.io/en/stable/quickstart.html#handling-unknown-fields