import logging from contextlib import asynccontextmanager from fastapi import FastAPI from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from app.api.router import api_router from app.config import settings engine = create_async_engine(settings.database_url, echo=settings.debug) async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async def get_db() -> AsyncSession: async with async_session() as session: yield session @asynccontextmanager async def lifespan(app: FastAPI): logging.basicConfig( level=getattr(logging, settings.log_level), format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", ) # LogHive 远程日志(仅当配置了 API Key 时启用) if settings.loghive_api_key: from loghive_client import LogHiveHandler handler = LogHiveHandler( project=settings.loghive_project, api_key=settings.loghive_api_key, endpoint=settings.loghive_endpoint, level=logging.INFO, ) logging.getLogger().addHandler(handler) logging.info("LogHive 日志系统已连接") from app.scheduler.jobs import shutdown_scheduler, start_scheduler start_scheduler() yield shutdown_scheduler() await engine.dispose() app = FastAPI( title="广西政府采购网公告监控系统", version="2.0.0", lifespan=lifespan, docs_url="/docs" if settings.debug else None, redoc_url=None, ) app.include_router(api_router) @app.get("/health") async def health(): return {"status": "ok"}