配置Fastapi路由器

2024-10-03 19:27:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在coupe中声明了router with middleware,并为某些抽象端点寻址调用中可能发生的任何异常添加了通用处理程序:

app = fastapi.FastAPI(openapi_url='/api/v1/openapi.json')
app.include_router(v1.api_router, prefix='/api/v1')
app.add_middleware(middlewares.ClientIPMiddleware)

@app.exception_handler(starlette.exceptions.HTTPException)
async def on_request_exception_handler(
    request: fastapi.Request,
    exc: starlette.exceptions.HTTPException,
):
    return fastapi.responses.JSONResponse(
        status_code=exc.status_code,
        content={
            'detail': exc.detail,
            'status': exc.status,
        },
    )

class ClientIPMiddleware(starlette.middleware.base.BaseHTTPMiddleware):
    async def dispatch(self, request: fastapi.Request, call_next: typing.Callable):
        request.state.client_ip = get_client_ip(request.headers)

        return await call_next(request)

ClientIPMiddleware类中,我必须重构并添加如下内容:

try:
   response = await call_next(request)
   if request.method != 'GET':
       if response.status_code == 200:
           return fastapi.responses.JSONResponse(
               status_code=200,
               content={'status': 'ok'},
           )
   return response
except Exception as e:
    pass

这里我只需要两种机制:一种用于捕获端点级别上可能出现的所有错误,另一种用于获取序列化响应,或者使用status_codestatus消息获取JSONResponse。在代码的最后一个片段中try/except块是奇怪的,因为它无法捕捉到任何错误。有没有更好的解决方案来实现这一目标?要向app实例添加自定义或原始装饰器吗


Tags: apiappreturnrequeststatuscodecallmiddleware