Spaces:
Running
Running
| """HTTP 客户端:httpx 全局连接池 + 超时控制。 | |
| 替代原 Netlify 版的 fetch + AbortController。 | |
| """ | |
| from __future__ import annotations | |
| from typing import Optional | |
| import httpx | |
| from .config import get_settings | |
| _client: Optional[httpx.AsyncClient] = None | |
| def get_http_client() -> httpx.AsyncClient: | |
| global _client | |
| if _client is None or _client.is_closed: | |
| settings = get_settings() | |
| timeout = httpx.Timeout( | |
| timeout=settings.upstream_timeout_ms / 1000.0, | |
| connect=10.0, | |
| read=settings.upstream_stream_timeout_ms / 1000.0, | |
| ) | |
| _client = httpx.AsyncClient( | |
| timeout=timeout, | |
| limits=httpx.Limits( | |
| max_connections=100, | |
| max_keepalive_connections=20, | |
| keepalive_expiry=30.0, | |
| ), | |
| http2=False, | |
| follow_redirects=False, | |
| ) | |
| return _client | |
| async def close_http_client() -> None: | |
| global _client | |
| if _client is not None and not _client.is_closed: | |
| await _client.aclose() | |
| _client = None | |