我希望使用棉花糖为我的api端点添加验证。
我遇到了如何正确验证此块的问题。最终目标是确保展示次数为正数。
非常感谢您提供的任何帮助或见解。第一次使用棉花糖。
Json示例:
{
"mode": [
{
"type": "String",
"values": {
"visits": 1000,
"budget": 400
},
"active": true
}
]
}
尝试验证的示例代码
class ValidateValues(BaseSchema):
visits = fields.Int(allow_none=True, validate=[validate.Range(min=0, error="Value must be greater than 0")])
budget = fields.Int(allow_none=True, validate=[validate.Range(min=0, error="Value must be greater than 0")])
class ModeSchema(BaseSchema):
type = fields.String(required=True)
active = fields.Boolean(required=True)
values = fields.Nested(ValidateValues)
class JsonSchema(BaseSchema):
mode = fields.List(fields.Dict(fields.Nested(ModeSchema, many=True)))
当前结果
{
"mode": {
"0": {
"type": {
"key": [
"Invalid type."
]
},
"values": {
"key": [
"Invalid type."
]
},
"active": {
"key": [
"Invalid type."
]
}
}
}
}
答案 0 :(得分:1)
您仅使用Nested
个字段的列表。在这里无需Dict
。
由于您将many=True
字段放在Nested
字段中,因此不需要List
。
尝试一下:
class JsonSchema(BaseSchema):
mode = fields.List(fields.Nested(ModeSchema))