44 lines
1.2 KiB
Python
44 lines
1.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Shared requests.Session pooling for plugins.
|
|
|
|
Goal: reuse TCP connections/cookies across multiple HTTP calls within a Kodi session.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any, Dict, Optional
|
|
|
|
try: # pragma: no cover - optional dependency
|
|
import requests
|
|
except Exception: # pragma: no cover
|
|
requests = None
|
|
|
|
_SESSIONS: Dict[str, Any] = {}
|
|
|
|
|
|
def get_requests_session(key: str, *, headers: Optional[dict[str, str]] = None):
|
|
"""Return a cached `requests.Session()` for the given key."""
|
|
if requests is None:
|
|
raise RuntimeError("requests ist nicht verfuegbar.")
|
|
key = (key or "").strip() or "default"
|
|
session = _SESSIONS.get(key)
|
|
if session is None:
|
|
session = requests.Session()
|
|
_SESSIONS[key] = session
|
|
if headers:
|
|
try:
|
|
session.headers.update({str(k): str(v) for k, v in headers.items() if k and v})
|
|
except Exception:
|
|
pass
|
|
return session
|
|
|
|
|
|
def close_all_sessions() -> None:
|
|
"""Close and clear all pooled sessions."""
|
|
for session in list(_SESSIONS.values()):
|
|
try:
|
|
session.close()
|
|
except Exception:
|
|
pass
|
|
_SESSIONS.clear()
|