5

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

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
marc
  • 527
  • 6
  • 23

1 Answers1

14

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.

marc
  • 527
  • 6
  • 23