2025-04-30 04:39:36 +08:00

43 lines
1.5 KiB
Python

# File: backend/app/main.py (Update - Add startup event)
# Description: FastAPI 应用入口 (添加数据库初始化)
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from app.api.v1.api import api_router as api_router_v1
import app.core.config # Ensure config is loaded
from app.db.database import create_db_and_tables # Import table creation function
from contextlib import asynccontextmanager
# --- Lifespan context manager for startup/shutdown events ---
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup actions
print("应用程序启动中...")
await create_db_and_tables() # Create database tables on startup
print("数据库表已检查/创建。")
# You can add the default assistant creation here if needed,
# but doing it in the service/model definition might be simpler for defaults.
yield
# Shutdown actions
print("应用程序关闭中...")
# Create FastAPI app with lifespan context manager
app = FastAPI(title="CherryAI Backend", version="0.1.0", lifespan=lifespan)
# --- CORS Middleware ---
origins = [ "http://localhost:3000", "http://127.0.0.1:3000" ]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# --- API Routers ---
app.include_router(api_router_v1, prefix="/api/v1")
# --- Root Endpoint ---
@app.get("/", tags=["Root"])
async def read_root():
return {"message": "欢迎来到 CherryAI 后端!"}