Skip to content

Question about typing when calling multipart.parse_form() #164

@clmbrdude

Description

@clmbrdude

I have a question about how to correctly use python typing when caliing the multipart.parse_form() function.

I will use the simple_example.py from https://multipart.fastapiexpert.com/#simple-example as an example:

When adding typing as follows I am getting errors from mypy:

from typing import Iterable, Any
from wsgiref.types import StartResponse

from multipart import multipart


def simple_app(environ: dict[str, Any], start_response: StartResponse) -> Iterable[bytes]:
    ret = []

    # The following two callbacks just append the name to the return value.
    def on_field(field: multipart.Field) -> None:
        ret.append(b"Parsed field named: %s" % (field.field_name,))

    def on_file(file: multipart.File) -> None:
        ret.append(b"Parsed file named: %s" % (file.field_name,))

    # Create headers object.  We need to convert from WSGI to the actual
    # name of the header, since this library does not assume that you are
    # using WSGI.
    headers = {'Content-Type': environ['CONTENT_TYPE']}
    if 'HTTP_X_FILE_NAME' in environ:
        headers['X-File-Name'] = environ['HTTP_X_FILE_NAME']
    if 'CONTENT_LENGTH' in environ:
        headers['Content-Length'] = environ['CONTENT_LENGTH']

    # Parse the form.
    multipart.parse_form(headers, environ['wsgi.input'], on_field, on_file)

    # Return something.
    start_response('200 OK', [('Content-type', 'text/plain')])
    ret.append(b'\n')
    return ret

from wsgiref.simple_server import make_server

httpd = make_server('', 8123, simple_app)
print("Serving on port 8123...")
httpd.serve_forever()

Running mypy yields the following:

$ mypy  .
simple_example.py:27: error: Argument 3 to "parse_form" has incompatible type "Callable[[Field], None]"; expected "Callable[[FieldProtocol], None] | None"  [arg-type]
simple_example.py:27: error: Argument 4 to "parse_form" has incompatible type "Callable[[File], None]"; expected "Callable[[FileProtocol], None] | None"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions