"""共享 httpx 异步客户端(连接池复用 + 生命周期管理)。 使用方: - src/llm/provider.py: LLM 调用 - src/data/bzzoiro.py: bzzoiro 比赛数据 / 积分榜 / 事件统计 生命周期由 FastAPI lifespan 管理(关闭时 aclose)。 调用方可通过 `timeout` 参数覆盖 per-request 超时。 """ from __future__ import annotations import httpx from src.core.config import settings _shared_client: httpx.AsyncClient | None = None def get_client() -> httpx.AsyncClient: """获取共享客户端(懒初始化)。""" global _shared_client if _shared_client is None or _shared_client.is_closed: _shared_client = httpx.AsyncClient(timeout=settings.HTTP_DEFAULT_TIMEOUT) return _shared_client async def close_client() -> None: """关闭共享客户端(在 FastAPI shutdown 时调用)。""" global _shared_client if _shared_client is not None and not _shared_client.is_closed: await _shared_client.aclose() _shared_client = None