Search code examples
pythonpython-3.xflaskmarshmallow

Marshmallow @validates does not raise error


all. I writing API project using Flask as the main framework and Marshmallow package for serializing JSON data. I want to create the player instance, but before create validate his nickname. View:

def create_player()
    ...
    try:
        data = player_schema.load(request_data)
        # when error raised excect case does not handle it
        # but data has 2 dicts: 
        # UnmarshalResult(data={}, errors={'nickname': ['Error!!!']})
    except ValidationError as err:
       return jsonify(err.messages), 400
    ...

Schema:

class PlayerSchema(Schema):

    nickname = fields.Str(required=True)
...

    @validates('nickname')
    def validate_nickname(self, value):
        raise ValidationError('Error!!!')

Solution

  • This is because by default in marshmallow 2, schemas don't raise on error.

    You need to pass strict meta argument:

    class PlayerSchema(Schema):
    
        nickname = fields.Str(required=True)
    
        class Meta:
            strict = True
    

    In marshmallow 3, schemas always raise on error.