'How to handle file upload validations using Flask-Marshmallow?

I'm working with Flask-Marshmallow for validating request and response schemas in Flask app. I was able to do simple validations for request.form and request.args when there are simple fields like Int, Str, Float etc.

I have a case where I need to upload a file using a form field - file_field. It should contain the file content.

How can I validate if this field is present or not and what is the format of file etc.

Is there any such field in Marshmallow that I can use like fields.Int() or fields.Str()

I have gone through the documentation here but haven't found any such field.



Solution 1:[1]

You can use fields.Raw:

import marshmallow

class CustomSchema(marshmallow.Schema):
  file = marshmallow.fields.Raw(type='file')

If you are using Swagger, you would then see something like this:

enter image description here

Then in your view you can access the file content with flask.request.files.

For a full example and more advanced topics, check out my project.

Solution 2:[2]

You can use either Field or Raw field to represent a general field, then set the correct OpenAPI properties for this field (i.e. type and format).

In OpenAPI 3, you should set type to string instead of file, then set format to binary or byte based on your file content:

from marshmallow import Schema, fields


class MySchema(Schema):
  file = fields.Raw(metadata={'type': 'string', 'format': 'binary'})

See the docs for more details.

By the way, from marshmallow 3.10.0, using keyword arguments to pass OpenAPI properties (description, type, example etc.) was deprecated and will be removed in marshmallow 4, use the metadata dict to pass them instead.

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 renatodamas
Solution 2 Grey Li