'How to validate Fields.Raw in Flask Marshmallow

I'm trying to set up a Webservice that accepts Images via POST methods. I'm using Python Flask as well as Flask-Apispec to create a Swagger documentation. I thus include this Marshmallow Schema to define which parameters are accepted:

class UploadRequestSchema(Schema):
    image = fields.Raw(type="file")

I now also want to document that only png-images are accepted and validate this to be true in Marshmallow.

Because of this, I've tried setting up a validator

class FileExtension(Validator)
    def __call__(self, value, **kwargs):
        print(value)
        print(type(value))
        for key in kwargs:
            print(key)
        
        //if filename ends in ".png"
        return true

class UploadRequestSchema(Schema):
    image = fields.Raw(type="file", validate=FileExtension())

However, the console output for this code is simply

[object File]
<class 'str'>

So value is simply a String with content "[object File]" and kwargs is empty. How can I access the file submitted to check its name? Alternatively, in what other way can I validate file uploads in Marshmallow?



Solution 1:[1]

The value should be an instance of Werkzueg's FileStorage object, you can validate against its filename or mimetype attributes.

from marshmallow import ValidationError


class FileExtension(Validator)

    def __call__(self, value, **kwargs):
        if not value.filename.endswith('.png'):
            raise ValidationError('PNG only!')
        return true

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Grey Li