Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
clmbrdude opened this issue Oct 2, 2024 · 0 comments
Open

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

clmbrdude opened this issue Oct 2, 2024 · 0 comments

Comments

@clmbrdude
Copy link

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant