96 lines
2.1 KiB
Python
96 lines
2.1 KiB
Python
"""
|
|
FastAPI 应用主文件
|
|
"""
|
|
import logging
|
|
from contextlib import asynccontextmanager
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from loguru import logger as loguru_logger
|
|
|
|
from app.core.config import settings
|
|
from app.models.base import init_db
|
|
from app.api.router import api_router
|
|
from app.services.scheduler_service import scheduler_service
|
|
|
|
# 配置日志
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
|
)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
"""应用生命周期管理"""
|
|
# 启动时执行
|
|
logger.info("Starting application...")
|
|
|
|
# 初始化数据库
|
|
init_db()
|
|
logger.info("Database initialized")
|
|
|
|
# 启动定时任务
|
|
scheduler_service.start()
|
|
scheduler_service.add_interaction_task()
|
|
scheduler_service.add_login_task(hour=8, minute=0)
|
|
scheduler_service.reset_daily_counters(hour=0, minute=1)
|
|
logger.info("Scheduler started")
|
|
|
|
yield
|
|
|
|
# 关闭时执行
|
|
logger.info("Shutting down application...")
|
|
scheduler_service.stop()
|
|
|
|
|
|
# 创建 FastAPI 应用
|
|
app = FastAPI(
|
|
title=settings.APP_NAME,
|
|
version=settings.APP_VERSION,
|
|
description="会会虚拟用户 AI 互动系统后端 API",
|
|
lifespan=lifespan
|
|
)
|
|
|
|
# 配置 CORS
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"], # 生产环境应该配置具体的域名
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
# 注册路由
|
|
app.include_router(api_router, prefix=settings.API_PREFIX)
|
|
|
|
|
|
@app.get("/")
|
|
async def root():
|
|
"""根路径"""
|
|
return {
|
|
"name": settings.APP_NAME,
|
|
"version": settings.APP_VERSION,
|
|
"status": "running"
|
|
}
|
|
|
|
|
|
@app.get("/health")
|
|
async def health_check():
|
|
"""健康检查"""
|
|
return {
|
|
"status": "healthy",
|
|
"scheduler_running": scheduler_service.is_running
|
|
}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
uvicorn.run(
|
|
"app.main:app",
|
|
host="0.0.0.0",
|
|
port=8000,
|
|
reload=settings.DEBUG
|
|
)
|