0

我已经在带有中间件的 coupe 中声明了路由器,并为在对某些抽象端点的寻址调用中可能发生的任何异常添加了通用处理程序:

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

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

4

0 回答 0