0

I am working on fastApi custom middleware it works fine until i add the line form = await request.form()

after addint that line it does not returns any response(connection timeout)

from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware


class AuthMiddleWare(BaseHTTPMiddleware):
    def __init__(
            self,
            app,
            some_attribute: str,
    ):
        super().__init__(app)
        self.some_attribute = some_attribute

    async def dispatch(self, request: Request, call_next):
        # do something with the request object, for example
        # content_type = request.headers.get('Content-Type')
        # print(content_type)

        before = await self.before_request(request)
        # process the request and get the response

        response = await call_next(request)
        self.after_request(request)
        print('call next executes')
        return response

    async def before_request(self, request: Request):
        try:
            print('------------------ before request starts ----------------')
            print(request.url)
            print(request.method)
            print(request.client.host)
            print(request.client.port)
            print(request.base_url)
            form = await request.form()
            firstname = form.get('firstname')
            print(firstname)
            print('------------------ before request ends ----------------')
        except:
            print('an exception occuret')

    def after_request(self, request: Request):
        pass

1 Answers1

0

If you print the exception (e.g. with print(traceback.format_exc()) or logger.exception("my message here") or similar) you'll see something like:

Traceback (most recent call last):
  File "C:\path\to\file.py", line 41, in before_request
    form = await request.form()
           ^^^^^^^^^^^^^^^^^^^^
  File "C:path\to\venv\Lib\site-packages\starlette\requests.py", line 255, in _get_form
    parse_options_header is not None
AssertionError: The `python-multipart` library must be installed to use form parsing.

So just install that package and it will work:

pip install python-multipart
Ben
  • 1,759
  • 1
  • 19
  • 23