You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

34 lines
836 B
Python

"""
Shared aiohttp ClientSession singleton.
Reuses a single TCP connection pool across all HTTP clients,
avoiding repeated TCP/TLS handshake overhead per request.
"""
import logging
from typing import Optional
import aiohttp
logger = logging.getLogger(__name__)
_session: Optional[aiohttp.ClientSession] = None
async def get_http_session() -> aiohttp.ClientSession:
"""Get or create the shared aiohttp ClientSession."""
global _session
if _session is None or _session.closed:
_session = aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=30),
)
return _session
async def close_http_session() -> None:
"""Close the shared session. Call on app shutdown."""
global _session
if _session and not _session.closed:
await _session.close()
_session = None