【发布时间】:2021-12-08 16:47:25
【问题描述】:
我们正在使用 Python FastAPI 编写一个 Web 服务,该服务将托管在 Kubernetes 中。出于审计目的,我们需要保存特定路由的请求/响应的原始 JSON 正文。 请求和响应 JSON 的主体大小约为 1MB,最好不要影响响应时间。 我们该怎么做?
【问题讨论】:
标签: python kubernetes fastapi audit-logging
我们正在使用 Python FastAPI 编写一个 Web 服务,该服务将托管在 Kubernetes 中。出于审计目的,我们需要保存特定路由的请求/响应的原始 JSON 正文。 请求和响应 JSON 的主体大小约为 1MB,最好不要影响响应时间。 我们该怎么做?
【问题讨论】:
标签: python kubernetes fastapi audit-logging
您可以尝试自定义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)
【讨论】:
您可以使用来自fastapi 的backgroundTasks 依赖项在后台运行一些任务,您的响应时间不会受到影响,请求不必等待这些任务完成。
【讨论】: