FastApi 中间件不会从 wait request.form() 返回

问题描述 投票:0回答:1

我正在开发 fastApi 自定义中间件,它工作正常,直到我添加该行

form = await request.form()

添加该行后,它不会返回任何响应(连接超时)

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
python authentication fastapi middleware
1个回答
0
投票

如果您打印异常(例如使用

print(traceback.format_exc())
logger.exception("my message here")
或类似内容),您将看到类似以下内容:

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.

所以只需安装该软件包即可工作:

pip install python-multipart
© www.soinside.com 2019 - 2024. All rights reserved.