import os import uvicorn from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from workflow_service.comfy.comfy_server import server_manager from workflow_service.database.api import init_db from workflow_service.config import Settings from workflow_service.routes import service, workflow, run, runx, monitor, comfy_server from workflow_service.comfy.comfy_queue import queue_manager settings = Settings() web_app = FastAPI(title="ComfyUI Workflow Service & Management API") # 配置跨域支持 web_app.add_middleware( CORSMiddleware, allow_origins=["*"], # 允许所有来源,生产环境中建议限制具体域名 allow_credentials=True, allow_methods=["*"], # 允许所有HTTP方法 allow_headers=["*"], # 允许所有请求头 ) web_app.include_router(service.service_router) web_app.include_router(workflow.workflow_router) web_app.include_router(run.run_router) web_app.include_router(runx.runx_router) web_app.include_router(monitor.monitor_router) web_app.include_router(comfy_server.router) @web_app.on_event("startup") async def startup_event(): """服务启动时,初始化数据库。""" await init_db() try: servers = await server_manager.get_all_servers() print(f"检测到 {len(servers)} 个 ComfyUI 服务器配置。") for server in servers: print(f" - 服务器: {server.http_url}") # 启动队列监控任务 await queue_manager.start_queue_monitor() print("队列监控任务已启动") except ValueError as e: print(f"错误: 无法在启动时获取服务器信息: {e}") @web_app.on_event("shutdown") async def shutdown_event(): """服务关闭时,停止队列监控任务。""" await queue_manager.stop_queue_monitor() print("队列监控任务已停止") if __name__ == "__main__": uvicorn.run( "workflow_service.main:web_app", host="0.0.0.0", port=18000, reload=True )