FastAPI Python:运行时警告:从未等待过协程“BaseHTTPMiddleware.call_next”

时间:2021-05-28 14:04:24

标签: python fastapi

我正在尝试在 FastAPI Python 中的中间件记录请求和响应,它运行良好,但我总是收到警告:

..../abc.py:102: RuntimeWarning: coroutine 'BaseHTTPMiddleware.call_next' was never awaited
  return _abc_subclasscheck(cls, subclass)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

...PyCharm Community Edition 2020.3.3\plugins\python-ce\helpers\pydev\_pydevd_bundle\pydevd_vars.py:432: RuntimeWarning: coroutine 'BaseHTTPMiddleware.call_next' was never awaited
  del updated_globals
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

如何解决。 请帮忙。谢谢! 我的代码:

main.py

app = FastAPI()
# logger = logging.getLogger(__name__)

config_path=Path(__file__).with_name("logging_config.json")
logger = CustomizeLogger.make_logger(config_path)
app.logger = logger

app.add_exception_handler(Exception, error_handle_business)
app.middleware('http')(catch_exceptions_middleware)

中间件.py

async def set_body(request: Request, body: bytes):
    async def receive() -> Message:
        return {"type": "http.request", "body": body}

    request._receive = receive


async def get_body(request: Request) -> bytes:
    body = await request.body()
    await set_body(request, body)
    return body


async def catch_exceptions_middleware(request: Request, call_next):
    try:
        request.app.logger.info(f"{request.method} {request.url}")
        routes = request.app.router.routes
        request.app.logger.info("Params:")
        for route in routes:
            match, scope = route.matches(request)
            if match == Match.FULL:
                for name, value in scope["path_params"].items():
                    request.app.logger.info(f"\t{name}: {value}")
        
        request_body = await get_body(request)
        request.app.logger.info("Body Request:")
        request.app.logger.info(f"\t{request_body.decode()}")
        response = await call_next(request)
        return response

0 个答案:

没有答案