71 lines
1.8 KiB
Python
71 lines
1.8 KiB
Python
"""
|
||
FastAPI 应用入口
|
||
"""
|
||
import os
|
||
from fastapi import FastAPI
|
||
from fastapi.middleware.cors import CORSMiddleware
|
||
from fastapi.staticfiles import StaticFiles
|
||
from contextlib import asynccontextmanager
|
||
|
||
from app.config import settings
|
||
from app.database import init_db
|
||
from app.routers import companies, reports, analysis, scheduler
|
||
from app.services.scheduler_service import scheduler_service
|
||
from app.utils.logger import logger
|
||
|
||
|
||
@asynccontextmanager
|
||
async def lifespan(app: FastAPI):
|
||
"""应用生命周期管理"""
|
||
# 启动时
|
||
logger.info(f"正在启动 {settings.APP_NAME}...")
|
||
|
||
# 初始化数据库
|
||
await init_db()
|
||
logger.info("数据库已初始化")
|
||
|
||
# 启动定时任务
|
||
if settings.SCHEDULER_ENABLED:
|
||
scheduler_service.start()
|
||
|
||
yield
|
||
|
||
# 关闭时
|
||
logger.info("应用正在关闭...")
|
||
scheduler_service.stop()
|
||
|
||
|
||
app = FastAPI(
|
||
title=settings.APP_NAME,
|
||
version=settings.APP_VERSION,
|
||
lifespan=lifespan
|
||
)
|
||
|
||
# CORS配置
|
||
app.add_middleware(
|
||
CORSMiddleware,
|
||
allow_origins=["*"],
|
||
allow_credentials=True,
|
||
allow_methods=["*"],
|
||
allow_headers=["*"],
|
||
)
|
||
|
||
# 注册路由
|
||
app.include_router(companies.router)
|
||
app.include_router(reports.router)
|
||
app.include_router(analysis.router)
|
||
app.include_router(scheduler.router)
|
||
|
||
# 挂载静态文件 (前端)
|
||
# 确保frontend目录存在
|
||
frontend_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "frontend")
|
||
if os.path.exists(frontend_dir):
|
||
app.mount("/", StaticFiles(directory=frontend_dir, html=True), name="frontend")
|
||
else:
|
||
logger.warning("前端目录不存在,API模式运行")
|
||
|
||
@app.get("/health")
|
||
async def health_check():
|
||
"""健康检查"""
|
||
return {"status": "ok", "version": settings.APP_VERSION}
|