可用 ORJSONResponse UJSONResponse替换 JSONResponse,貌似json解析更快
pip install orjson (使用 ORJSONResponse)
# coding: utf8
from fastapi import FastAPI,status
from fastapi.responses import Response,JSONResponse
from typing import Union
# 封装统一返回
def reponse(*, code=200, msg="success", data: Union[list, dict, str] = None) -> Response:
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
'code': code,
'msg': msg,
'data': data
}
)
app = FastAPI()
@app.get('/items')
async def items(key: str):
if key == "001":
return reponse(code=400, msg='No 001')
return reponse()
# uvicorn main:app --reload --host 0.0.0.0