【发布时间】:2020-03-02 20:51:37
【问题描述】:
我希望使用 Marshmallow 向我的 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."
]
}
}
}
}
【问题讨论】:
标签: python python-3.x flask flask-restful marshmallow