Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 25 additions & 13 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,31 +17,43 @@
"""
Main entry point for Sugar-AI application.
"""

import uvicorn
import logging
from sqlalchemy.orm import Session
import os

from app import create_app
from contextlib import asynccontextmanager
from fastapi import FastAPI
from app.database import get_db
from app.auth import sync_env_keys_to_db
from app.config import settings
from app import create_app

# setup logging
# Setup logging
logger = logging.getLogger("sugar-ai")

app = create_app()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""
Handles the startup and shutdown lifecycle of the application.
Replaces the deprecated @app.on_event("startup") and "shutdown".
"""
# --- Startup Logic ---
try:
db = next(get_db())
sync_env_keys_to_db(db)
logger.info(f"Starting Sugar-AI with model: {settings.DEFAULT_MODEL}")
except Exception as e:
logger.error(f"Failed to initialize app during startup: {e}")
raise e

yield

# --- Shutdown Logic ---
logger.info("Shutting down Sugar-AI...")

@app.on_event("startup")
async def startup_event():
"""Initialize data on app startup"""
db = next(get_db())
sync_env_keys_to_db(db)
logger.info(f"Starting Sugar-AI with model: {settings.DEFAULT_MODEL}")
app = create_app()
app.router.lifespan_context = lifespan

if __name__ == "__main__":
port = int(os.getenv("PORT", 8000))
logger.info(f"Starting Sugar-AI on port {port}")
uvicorn.run(app, host="0.0.0.0", port=port)