gpt4 book ai didi

python - 在中间件上下文中获取 starlette 请求正文

转载 作者:行者123 更新时间:2023-12-03 16:32:34 27 4
gpt4 key购买 nike

我有这样的中间件

class RequestContext(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint):
request_id = request_ctx.set(str(uuid4())) # generate uuid to request
body = await request.body()
if body:
logger.info(...) # log request with body
else:
logger.info(...) # log request without body

response = await call_next(request)
response.headers['X-Request-ID'] = request_ctx.get()
logger.info("%s" % (response.status_code))
request_ctx.reset(request_id)

return response
所以行 body = await request.body()卡住所有有正文的请求,我有来自所有请求的 504。在这种情况下,如何安全地读取请求正文?我只想记录请求参数。

最佳答案

我不会创建一个继承自 BaseHTTPMiddleware 的中间件,因为它有一些 issues , FastAPI 让您有机会创建自己的路由器,根据我的经验,这种方法更好。

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

from typing import Callable, List
from uuid import uuid4


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

async def custom_route_handler(request: Request) -> Response:
request_id = str(uuid4())
response: Response = await original_route_handler(request)

if await request.body():
print(await request.body())

response.headers["Request-ID"] = request_id
return response

return custom_route_handler


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


@router.post("/context")
async def non_default_router(bod: List[str] = Body(...)):
return bod


app.include_router(router)
按预期工作。
b'["string"]'
INFO: 127.0.0.1:49784 - "POST /context HTTP/1.1" 200 OK

关于python - 在中间件上下文中获取 starlette 请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64115628/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com