Files
lyroc/backend/main.py
2025-05-27 14:16:48 +08:00

87 lines
2.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'''
Date: 2025-05-06 09:26:51
LastEditors: 陈子健
LastEditTime: 2025-05-26 17:14:17
FilePath: /mac-lyric-vue/backend/main.py
'''
"""
lyroc 后端主程序
负责初始化应用和启动服务器
"""
import uvicorn
import os
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
# 导入自定义模块
from modules.websocket_manager import ConnectionManager
from modules.background_tasks import start_background_task, cancel_all_tasks, background_tasks
from modules.routes import register_routes
# 配置日志
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# 应用支持目录和歌词目录在lyrics模块中已定义
# Lifespan 上下文管理器,替代 on_event
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("正在启动API服务...")
try:
# 启动时创建后台任务
start_background_task(manager)
logger.info("后台任务已启动")
except Exception as e:
logger.error(f"启动后台任务失败: {e}")
yield # 应用正常运行
# 关闭时清理任务
try:
cancel_all_tasks()
logger.info("后台任务已关闭")
except Exception as e:
logger.error(f"关闭后台任务失败: {e}")
# 创建FastAPI应用
app = FastAPI(lifespan=lifespan)
# 确保在应用启动时直接启动任务(作为后备方案)
@app.on_event("startup")
async def startup_event():
# 仅当通过 lifespan 未启动任务时才启动
if not background_tasks:
logger.info("通过startup_event启动后台任务...")
try:
start_background_task(manager)
logger.info("后台任务通过startup_event成功启动")
except Exception as e:
logger.error(f"通过startup_event启动后台任务失败: {e}")
# 配置CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 创建WebSocket连接管理器
manager = ConnectionManager()
# 注册API路由
register_routes(app, manager)
if __name__ == "__main__":
# 从环境变量获取端口号如果未设置则默认使用5000
port = int(os.environ.get("PORT", 5000))
logger.info(f"启动后端服务器在端口: {port}")
uvicorn.run("main:app", host="127.0.0.1", port=port, reload=True)