Multipart Forms

Compatibility

CPython & MicroPython

Required Microdot source files

Required external dependencies

None

Examples

The multipart extension handles multipart forms, including those that have file uploads.

The with_form_data decorator provides the simplest way to work with these forms. With this decorator added to the route, whenever the client sends a multipart request the request.form and request.files properties are populated with the submitted data. For form fields the field values are always strings. For files, they are instances of the FileUpload class.

Example:

from microdot.multipart import with_form_data

@app.post('/upload')
@with_form_data
async def upload(request):
    print('form fields:', request.form)
    print('files:', request.files)

One disadvantage of the @with_form_data decorator is that it has to copy any uploaded files to memory or temporary disk files, depending on their size. The FileUpload.max_memory_size attribute can be used to control the cutoff size above which a file upload is transferred to a temporary file.

A more performant alternative to the @with_form_data decorator is the FormDataIter class, which iterates over the form fields sequentially, giving the application the option to parse the form fields on the fly and decide what to copy and what to discard. When using FormDataIter the request.form and request.files attributes are not used.

Example:

from microdot.multipart import FormDataIter

@app.post('/upload')
async def upload(request):
    async for name, value in FormDataIter(request):
        print(name, value)

For fields that contain an uploaded file, the value returned by the iterator is the same FileUpload instance. The application can choose to save the file with the save() method, or read it with the read() method, optionally passing a size to read it in chunks. The copy() method is also available to apply the copying logic used by the @with_form_data decorator, which is inefficient but allows the file to be set aside to be processed later, after the remaining form fields.