对现场数据的烧瓶棉花糖验证不起作用

flask-marshmallow validation on field data not working

嗨,我做了这样的 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))

我想发送这样的请求:

{   
    "1faf8f07-2977-180e-7bc2-b5adf8badasda": {"student_id":11210687,"room_id":"100"}
}

但是出现这样的错误

{
    "rooms": {
        "1faf8f07-2977-180e-7bc2-b5adf8badasda": {
            "value": {
                "student_id": {
                    "key": [
                        "Not a valid integer."
                    ]
                },
                "room_id": {
                    "key": [
                        "Not a valid integer."
                    ]
                }
            }
        }
    }
}

如何以所需格式正确传递数据?

Integer类型支持转换。

来自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.

所以尝试:

class MyRequestDto(Schema):
    @pre_load
    def wrap_data(self, in_data, **kwargs):
        return {"rooms": in_data}

    rooms = Dict(String, Dict(String, Integer))

它将自动处理 room_idstr

如果你想保持 room_idstr 那么你需要定义一个 Custom Field.

示例:

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))