【fastapi封装exec】

如果你遇到pydantic验证和自己想要的response不一致,不妨来看看这段代码,优雅的将pydantic的类型提示错误修改为自己response的msg

import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.responses import JSONResponse
import json

app = FastAPI()


# @app.exception_handler(StarletteHTTPException)
# async def http_exception_handler(request, exc):
#     return PlainTextResponse(str(exc.detail), status_code=exc.status_code)

resp_dict = {}
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    exce = json.loads(str(exc.json()))
    return JSONResponse({
        "code": 1,
        'msg': {
            "explain":"参数错误",
            "detail":exce,
        },
        "data": []
    })

from pydantic import BaseModel
class ItemSchema(BaseModel):
    item_id:int
    item_name:int
@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id == 3:
        raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
    return resp_dict

@app.post("/items")
async def read_item(itemscheme:ItemSchema):
    itemscheme = itemscheme.dict()
    resp_dict.update(**itemscheme)
    return resp_dict

if __name__ == '__main__':
    uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)
http://127.0.0.1:8000/items post
application/json
{
    "item_id":"a",
    "item_name":"a"
}
response:
>>>
{
    "code": 1,
    "msg": {
        "explain": "参数错误",
        "detail": [
            {
                "loc": [
                    "body",
                    "item_id"
                ],
                "msg": "value is not a valid integer",
                "type": "type_error.integer"
            },
            {
                "loc": [
                    "body",
                    "item_name"
                ],
                "msg": "value is not a valid integer",
                "type": "type_error.integer"
            }
        ]
    },
    "data": []
}
posted @ 2021-09-28 14:33  GokuBlog  阅读(125)  评论(0编辑  收藏  举报