Files
ProxyPool/app/api/lifespan.py
祀梦 f09a8e16c4 fix: 修复爬虫网络层、验证队列卡死及 API 500 错误
- 修复 BaseHTTPPlugin 连接池、并发控制、异常日志、超时策略
- 修复/增强 8 个爬虫插件的稳定性和 fallback 机制
- 清理 validation_tasks 表 4 万+ pending 任务,避免队列卡死
- 修复 app/api/main.py 缺失全局 app 实例导致的 500 错误
- 提升前端 Axios 超时到 120 秒,避免请求断开
- 修复插件统计持久化和调度器生命周期问题
2026-04-04 19:27:36 +08:00

50 lines
1.7 KiB
Python

"""应用生命周期管理"""
import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI
from app.core.db import init_db, get_db
from app.core.config import settings as app_settings
from app.core.log import logger
from app.api.deps import create_scheduler_service
from app.repositories.settings_repo import SettingsRepository
settings_repo = SettingsRepository()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用启动和关闭时的生命周期管理"""
# 初始化数据库
await init_db()
# 创建调度器并挂载到 app.state
scheduler_service = create_scheduler_service()
app.state.scheduler_service = scheduler_service
app.state.validation_queue = scheduler_service.validation_queue
# 加载设置并决定是否启动调度器
try:
async with get_db() as db:
settings = await settings_repo.get_all(db)
scheduler_service.interval_minutes = settings.get(
"validate_interval_minutes", app_settings.validator_timeout
)
if settings.get("auto_validate", True):
await scheduler_service.start()
except Exception as e:
logger.error(f"Failed to load settings on startup: {e}")
logger.info("API server started")
yield
# 关闭调度器
if scheduler_service._validate_task and not scheduler_service._validate_task.done():
scheduler_service._validate_task.cancel()
try:
await scheduler_service._validate_task
except asyncio.CancelledError:
pass
await scheduler_service.stop()
await scheduler_service.validation_queue.validator.close()
logger.info("API server shutdown")