问题描述
我已经在带有中间件的 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_code
和 {{1 }} 信息。在代码的最后一个片段中,status
块很奇怪,因为它无法在那里捕获任何错误。有没有更好的解决方案来达到目标?要将自定义或原始装饰器添加到 try/except
实例?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)