FastAPI 動態(tài)建模

1、初衷

FastAPI 官方示例中路由,模型需要重復(fù)內(nèi)容相對較多,考慮簡化方案,可采用模板代碼生成,或動態(tài)建模簡化,現(xiàn)通過后者驗(yàn)證。

2、實(shí)現(xiàn)

from typing import List
from fastapi import FastAPI
from starlette.requests import Request
from pydantic import BaseModel, create_model
import json

app = FastAPI()

config_json = [{
        "table": "User",
        "columns": [{
            "code": "UserID",
            "c_name": "用戶編號",
            "e_name": "user_id",
            "type": "int"
        },{
            "code": "UserName",
            "c_name": "用戶名稱",
            "e_name": "user_name",
            "type": "string"
        }]
    },
    {
        "table": "Role",
        "columns": [{
            "code": "RoleID",
            "c_name": "角色編號",
            "e_name": "role_id",
            "type": "int"
        },{
            "code": "RoleName",
            "c_name": "用戶名稱",
            "e_name": "role_name",
            "type": "string"
        }]
    }
]


def load_api():
    for temp in config_json:
        # 模型參數(shù)
        kwargs = {}

        # 設(shè)置參數(shù)
        for col in temp["columns"]:
            if col["type"] == "int":
                kwargs[col["code"]] = 1
            elif col["type"] == "string":
                kwargs[col["code"]] = (str,...)

        DynamicFoobarModel = create_model(temp["table"], **kwargs)

        @app.get("/" + temp["table"])
        async def read_item(request: Request, skip: int = 0, limit: int = 10):
            # 如果想獲取路由,在處理方法中不能直接使用 temp["table"] , 會被覆蓋為最后一個值,可以使用request 獲取
            return {"type": "get" , "route:": request.url.path}
        @app.post("/" + temp["table"])
        async def update_item(request: Request, item: DynamicFoobarModel):
            return {"type": "post" , "route:": request.url.path , "kwargs": item.to_string()}


if __name__ == '__main__':
    load_api()
    import uvicorn
    uvicorn.run(app, host='127.0.0.1', port=8000)

# 避免命令行啟動,修改為 run
# 命令行啟動方式為:uvicorn 文件名:app --reload
生成統(tǒng)一API

Get提交

Post提交
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容