Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 775
marc Avatar asked Dec 13 '22 17:12

marc


1 Answers

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

Just creating a new class which extends from fields.Field and override the _validate method as it 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 yout time.

like image 55
marc Avatar answered Dec 29 '22 10:12

marc