Skip to content

Commit e4f5d4f

Browse files
committed
implement thread-local connection handling for shared instances
1 parent c0aebaa commit e4f5d4f

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

openapi_python_sdk/client.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import json
2+
import threading
23
from typing import Any, Dict
34

45
import httpx
@@ -15,13 +16,33 @@ class Client:
1516
"""
1617

1718
def __init__(self, token: str, client: Any = None, timeout: float = 30.0):
18-
self.client = client if client is not None else httpx.Client(timeout=timeout)
19+
self._client = client
20+
self._thread_local = threading.local()
21+
self.timeout = timeout
1922
self.auth_header: str = f"Bearer {token}"
2023
self.headers: Dict[str, str] = {
2124
"Authorization": self.auth_header,
2225
"Content-Type": "application/json",
2326
}
2427

28+
@property
29+
def client(self) -> Any:
30+
"""
31+
Thread-safe access to the underlying HTTP client.
32+
If a custom client was provided at initialization, it is returned.
33+
Otherwise, a thread-local httpx.Client is created and returned.
34+
"""
35+
if self._client is not None:
36+
return self._client
37+
38+
if not hasattr(self._thread_local, "client"):
39+
self._thread_local.client = httpx.Client(timeout=self.timeout)
40+
return self._thread_local.client
41+
42+
@client.setter
43+
def client(self, value: Any):
44+
self._client = value
45+
2546
def __enter__(self):
2647
"""Enable use as a synchronous context manager."""
2748
return self

0 commit comments

Comments
 (0)