fix: use lifespan context manager instead of deprecated on_event for startup
This commit is contained in:
+34
-21
@@ -10,6 +10,7 @@ from routers import docker_router, gitea, files, terminal, system, chat_summary,
|
||||
import auth_service as auth_module
|
||||
import config
|
||||
from rbac import require_page
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import asyncio
|
||||
import httpx
|
||||
@@ -21,8 +22,40 @@ from config import TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID, CORS_ORIGINS, SECRET_KE
|
||||
|
||||
_tz_cst = timezone(timedelta(hours=8))
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# Startup
|
||||
print("=== Application Startup ===")
|
||||
|
||||
# Initialize OPC database
|
||||
from db import opc_db
|
||||
try:
|
||||
await opc_db.init_db()
|
||||
print("OPC database initialized")
|
||||
except Exception as e:
|
||||
print(f"Failed to initialize OPC database: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
# Start agent executor service
|
||||
from services import agent_executor
|
||||
try:
|
||||
asyncio.create_task(agent_executor.start_executor())
|
||||
print("Agent executor service started")
|
||||
except Exception as e:
|
||||
print(f"Failed to start agent executor: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
asyncio.create_task(monitor_containers())
|
||||
|
||||
yield
|
||||
|
||||
# Shutdown
|
||||
print("=== Application Shutdown ===")
|
||||
|
||||
limiter = Limiter(key_func=get_remote_address)
|
||||
app = FastAPI(title="NAS Dashboard")
|
||||
app = FastAPI(title="NAS Dashboard", lifespan=lifespan)
|
||||
app.state.limiter = limiter
|
||||
|
||||
app.add_middleware(
|
||||
@@ -111,26 +144,6 @@ async def monitor_containers():
|
||||
|
||||
await asyncio.sleep(60)
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup_event():
|
||||
# Initialize OPC database
|
||||
from db import opc_db
|
||||
try:
|
||||
await opc_db.init_db()
|
||||
logging.getLogger(__name__).info("OPC database initialized")
|
||||
except Exception as e:
|
||||
logging.getLogger(__name__).error("Failed to initialize OPC database: %s", e)
|
||||
|
||||
# Start agent executor service
|
||||
from services import agent_executor
|
||||
try:
|
||||
asyncio.create_task(agent_executor.start_executor())
|
||||
logging.getLogger(__name__).info("Agent executor service started")
|
||||
except Exception as e:
|
||||
logging.getLogger(__name__).error("Failed to start agent executor: %s", e)
|
||||
|
||||
asyncio.create_task(monitor_containers())
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
Reference in New Issue
Block a user