pythonformsflaskflask-wtformsflask-marshmallow

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

  • 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.