【问题标题】:Marshmallow not giving errors棉花糖不报错
【发布时间】:2016-03-15 11:28:18
【问题描述】:

如果我使用 Marshmallow 创建这样的架构:

class TempSchema(Schema):
    id = fields.Int()
    email = fields.Str(required=True,
                   validate=validate.Email(error='Not a valid email address'))
    password = fields.Str(required=True,
                      validate=[validate.Length(min=6, max=36)],
                      load_only=True)

然后我会做类似的事情:

temp = TempSchema()
temp.dumps({'email':123})

我预计会出现错误,但我得到:

MarshalResult(data='{"email": "123"}', errors={})

为什么这个或其他任何东西都没有显示为错误?

【问题讨论】:

    标签: python schema marshmallow


    【解决方案1】:

    验证只发生在反序列化(使用Schema.load),而不是序列化(Schema.dump)。

    data, errors = schema.load({'email': '123'})
    print(errors)
    # {'email': ['Not a valid email address'], 'password': ['Missing data for required field.']}
    

    如果不需要反序列化的数据,可以使用Schema.validate

    errors = schema.validate({'email': '123'})
    print(errors)
    # {'email': ['Not a valid email address'], 'password': ['Missing data for required field.']}
    

    【讨论】:

      猜你喜欢
      • 2017-05-12
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 2018-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多