[英]flask-marshmallow validation on field data not working
Hi I made my dto something like this嗨,我让我的 dto 像这样
class MyRequestDto(ma.Schema):
@pre_load
def wrap_data(self, in_data, **kwargs):
return {"rooms": in_data}
rooms = ma.Dict(ma.String, ma.Dict(ma.Integer, ma.String))
and I want to send request something like this:我想发送这样的请求:
{
"1faf8f07-2977-180e-7bc2-b5adf8badasda": {"student_id":11210687,"room_id":"100"}
}
but getting error like this但得到这样的错误
{
"rooms": {
"1faf8f07-2977-180e-7bc2-b5adf8badasda": {
"value": {
"student_id": {
"key": [
"Not a valid integer."
]
},
"room_id": {
"key": [
"Not a valid integer."
]
}
}
}
}
}
kindly guide what I can do to pass data correctly In required format.请指导我可以做些什么来以所需的格式正确传递数据。 And please before down vote tell me reason why you doing this as I am stuck badly.
请在投票之前告诉我你为什么这样做,因为我被严重卡住了。 thanks
谢谢
Integer
type supports cast. Integer
类型支持演员表。
From the documentation :从文档中:
class marshmallow.fields.Integer(*, strict: bool = False, **kwargs)[source]
An integer field.
Parameters
strict – If True, only integer types are valid. Otherwise, any value castable to int is valid.
kwargs – The same keyword arguments that Number receives.
So try:所以试试:
class MyRequestDto(Schema):
@pre_load
def wrap_data(self, in_data, **kwargs):
return {"rooms": in_data}
rooms = Dict(String, Dict(String, Integer))
It will automatically handle the str
for room_id
.它将自动处理
room_id
的str
。
If you want to keep room_id
as str
then you need to define a Custom Field .如果您想将
room_id
保留为str
,那么您需要定义一个Custom Field 。
Example:例子:
class CustomField(Field):
def _serialize(self, value, attr, obj, **kwargs):
if isinstance(value, (str, int)):
return value
raise ValidationError("Value is not int or str")
def _deserialize(self, value, attr, data, **kwargs):
if isinstance(value, (str, int)):
return value
raise ValidationError("Value is not int or str")
class MyRequestDto(Schema):
@pre_load
def wrap_data(self, in_data, **kwargs):
return {"rooms": in_data}
rooms = Dict(String, Dict(String, CustomField))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.