Search code examples
pythonpython-3.xodmmarshmallow

Python marshmallow blob/bytes field


I've been searching for a while about how to validate if a dictionary's key has value (required) and this value's type is bytes using Marshmallow, but I didn't find anything that could work.

There's no "basic" field type in the Marshmallow reference documentaiton which matches with bytes data type. So I asume that it has to be a custom field.

Does anyone has already faced this problem? Any clue to solve it?

Thank you


Solution

  • Well... the solution was quite easy, just reading the correct docs page I figured out how to solve my problem.

    Just create a new class which extends from fields. Field and override the _validate method as follows:

    class BytesField(fields.Field):
        def _validate(self, value):
            if not isinstance(value, bytes):
                raise ValidationError('Invalid input type.')
    
            if value is None or value == b'':
                raise ValidationError('Invalid value')
    

    And here's the marshmallow schema:

    class MySchema(Schema):
        // ...
        field = BytesField(required=True)
        // ...
    

    That's all. Sorry for wasting your time.