FastAPI 动态建模

2020-06-17  本文已影响0人  过桥

1、初衷

FastAPI 官方示例中路由,模型需要重复内容相对较多,考虑简化方案,可采用模板代码生成,或动态建模简化,现通过后者验证。

2、实现

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:
        # 模型参数
        kwargs = {}

        # 设置参数
        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
生成统一API
Get提交
Post提交
上一篇下一篇

猜你喜欢

热点阅读