【问题标题】:How to log raw HTTP request/response in Python FastAPI如何在 Python FastAPI 中记录原始 HTTP 请求/响应
【发布时间】:2021-12-08 16:47:25
【问题描述】:

我们正在使用 Python FastAPI 编写一个 Web 服务,该服务将托管在 Kubernetes 中。出于审计目的,我们需要保存特定路由的请求/响应的原始 JSON 正文。 请求和响应 JSON 的主体大小约为 1MB,最好不要影响响应时间。 我们该怎么做?

【问题讨论】:

  • Related topic 您可以使用中间件或 apirouter 和 loguru 记录器和选项 enqueue=True。这将使您不会影响响应时间。

标签: python kubernetes fastapi audit-logging


【解决方案1】:

您可以尝试自定义APIRouter,就像在 FastAPI 官方文档中一样:

import time
from typing import Callable

from fastapi import APIRouter, FastAPI, Request, Response
from fastapi.routing import APIRoute


class TimedRoute(APIRoute):
    def get_route_handler(self) -> Callable:
        original_route_handler = super().get_route_handler()

        async def custom_route_handler(request: Request) -> Response:
            before = time.time()
            response: Response = await original_route_handler(request)
            duration = time.time() - before
            response.headers["X-Response-Time"] = str(duration)
            print(f"route duration: {duration}")
            print(f"route response: {response}")
            print(f"route response headers: {response.headers}")
            return response

        return custom_route_handler


app = FastAPI()
router = APIRouter(route_class=TimedRoute)


@app.get("/")
async def not_timed():
    return {"message": "Not timed"}


@router.get("/timed")
async def timed():
    return {"message": "It's the time of my life"}


app.include_router(router)

【讨论】:

    【解决方案2】:

    您可以使用来自fastapi 的backgroundTasks 依赖项在后台运行一些任务,您的响应时间不会受到影响,请求不必等待这些任务完成。

    https://fastapi.tiangolo.com/tutorial/background-tasks/

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center。
    猜你喜欢
    • 2012-02-08
    • 2010-11-05
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    相关资源
    最近更新 更多