Skip to content

Commit c0aebaa

Browse files
committed
make OauthClient thread-safe using threading.local
1 parent 7869447 commit c0aebaa

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

openapi_python_sdk/oauth_client.py

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

45
import httpx
@@ -13,7 +14,9 @@ class OauthClient:
1314
"""
1415

1516
def __init__(self, username: str, apikey: str, test: bool = False, client: Any = None, timeout: float = 30.0):
16-
self.client = client if client is not None else httpx.Client(timeout=timeout)
17+
self._client = client
18+
self._thread_local = threading.local()
19+
self.timeout = timeout
1720
self.url: str = TEST_OAUTH_BASE_URL if test else OAUTH_BASE_URL
1821
self.auth_header: str = (
1922
"Basic " + base64.b64encode(f"{username}:{apikey}".encode("utf-8")).decode()
@@ -23,6 +26,24 @@ def __init__(self, username: str, apikey: str, test: bool = False, client: Any =
2326
"Content-Type": "application/json",
2427
}
2528

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

0 commit comments

Comments
 (0)