83 lines
2.4 KiB
Python
83 lines
2.4 KiB
Python
import uvicorn
|
|
from fastapi import FastAPI
|
|
from models.schemas.system import InitStatusResponse, InitConfigRequest
|
|
from core.config import load_init_config, save_init_config
|
|
from core.db import init_tortoise, close_tortoise
|
|
from contextlib import asynccontextmanager
|
|
import logging
|
|
|
|
async def is_init():
|
|
init_config = await load_init_config()
|
|
init_status = init_config.get("is_init")
|
|
return init_status
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
|
|
if await is_init():
|
|
app.logger.info("初始化数据库")
|
|
await init_tortoise()
|
|
|
|
yield
|
|
|
|
app.logger.info("关闭数据库")
|
|
await close_tortoise()
|
|
|
|
|
|
def create_app():
|
|
app = FastAPI(title="Workflow API", version="1.0.0")
|
|
|
|
@app.get("/")
|
|
async def root():
|
|
return {"message": "hello"}
|
|
|
|
@app.get(
|
|
"/check_init",
|
|
tags=["System"],
|
|
description="系统是否初始化",
|
|
response_model=InitStatusResponse,
|
|
)
|
|
async def check_init():
|
|
return InitStatusResponse(data=await is_init())
|
|
|
|
@app.post(
|
|
"/init_system",
|
|
tags=["System"],
|
|
description="系统初始化",
|
|
response_model=InitStatusResponse,
|
|
)
|
|
async def init_system(request: InitConfigRequest):
|
|
app.logger.info("init_system")
|
|
try:
|
|
init_config = await load_init_config()
|
|
if init_config.get('is_init'):
|
|
return InitStatusResponse(data=True)
|
|
# 保存配置
|
|
init_config["db_type"] = request.db_type
|
|
init_config["db_host"] = request.db_host
|
|
init_config["db_port"] = request.db_port
|
|
init_config["db_user"] = request.db_user
|
|
init_config["db_password"] = request.db_password
|
|
init_config["db_name"] = request.db_name
|
|
init_config["is_init"] = True
|
|
|
|
init_success = await init_tortoise(request.db_type, init_config)
|
|
|
|
if init_success:
|
|
await save_init_config(init_config)
|
|
return InitStatusResponse(data=True)
|
|
|
|
return InitStatusResponse(success=False, message="初始化数据库失败")
|
|
except Exception as e:
|
|
return InitStatusResponse(success=False, message=str(e))
|
|
return app
|
|
|
|
|
|
app = create_app()
|
|
app.logger = logging.getLogger("workflow")
|
|
app.logger.setLevel(logging.INFO)
|
|
|
|
if __name__ == "__main__":
|
|
uvicorn.run("main:app", host="0.0.0.0", port=8080, reload=True)
|