1. 安装依赖包
anyio==3.6.1 
fastapi==0.79.0 
pydantic==1.9.1 
sniffio==1.2.0 
starlette==0.19.1
h11==0.13.0 
uvicorn==0.18.2
pymongo==4.2.0
  1. 自定义response类
from fastapi.responses import Response
from bson.json_util import dumps

class CoustomResponse(Response):
    def __init__(self, content, msg, status,error=None):
        if msg:
            content['msg'] = msg
        if error:
            content['error'] = error
        super().__init__(
            content=dumps(content),
            media_type="application/json",
            status_code=status
        )

我们只需要在这里将我们的逻辑处理完,并将数据放到content中就可以了
3. demo

from fastapi import FastAPI,status
import uvicorn
from fastapi.responses import Response
from bson.json_util import dumps

class CoustomResponse(Response):
    def __init__(self, content, msg, status,error=None):
        if msg:
            content['msg'] = msg
        if error:
            content['error'] = error
        super().__init__(
            content=dumps(content),
            media_type="application/json",
            status_code=status
        )

app = FastAPI(default_response_class=CoustomResponse)

@app.get('/test')
async def test():
    return CoustomResponse(content={"haha":"haha"},msg={"data":"test"},error=None,status=status.HTTP_200_OK)

if __name__=='__main__':
    uvicorn.run('main:app',host='0.0.0.0',port=9999,reload=True)





https://stackoverflow.com/questions/63960879/fastapi-custom-response-class-as-default-response-class

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐