Skip to content
This repository was archived by the owner on Sep 25, 2025. It is now read-only.

Commit 0f57424

Browse files
committed
Lazily instantiate the session
1 parent 1eb4876 commit 0f57424

2 files changed

Lines changed: 22 additions & 5 deletions

File tree

pydepsdev/api.py

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@
4848

4949

5050
class DepsdevAPI:
51-
session: aiohttp.ClientSession
51+
session: Optional[aiohttp.ClientSession]
5252
headers: Dict[str, str]
5353
timeout_duration: float
5454
max_retries: int
@@ -71,7 +71,7 @@ def __init__(
7171
base_backoff (float): Initial backoff interval in seconds.
7272
max_backoff (float): Maximum backoff interval in seconds.
7373
"""
74-
self.session = aiohttp.ClientSession()
74+
self.session = None
7575
self.headers = {"Content-Type": "application/json"}
7676
self.timeout_duration = timeout_duration
7777
self.max_retries = max_retries
@@ -85,22 +85,37 @@ def __init__(
8585
max_backoff,
8686
)
8787

88+
async def _getsession(self) -> aiohttp.ClientSession:
89+
"""
90+
Lazily instantiate and return an aiohttp.ClientSession
91+
within a running event loop.
92+
93+
Returns:
94+
aiohttp.ClientSession: The current aiohttp client session.
95+
"""
96+
if self.session is None:
97+
self.session = aiohttp.ClientSession()
98+
return self.session
99+
88100
async def close(self) -> None:
89101
"""
90102
Close the underlying HTTP session.
91103
92104
Returns:
93105
None
94106
"""
95-
await self.session.close()
107+
if self.session is not None:
108+
await self.session.close()
109+
self.session = None
96110

97111
async def __aenter__(self) -> "DepsdevAPI":
98112
"""
99-
Enter the async context.
113+
Enter the async context. Ensures the session is created.
100114
101115
Returns:
102116
DepsdevAPI: The current API client instance.
103117
"""
118+
await self._getsession()
104119
return self
105120

106121
async def __aexit__(
@@ -145,6 +160,7 @@ async def fetch_data(
145160
Raises:
146161
APIError: On HTTP client/server error or network failure.
147162
"""
163+
session = await self._getsession()
148164
attempt = 0
149165
while attempt <= self.max_retries:
150166
logger.info(
@@ -156,7 +172,7 @@ async def fetch_data(
156172
self.max_retries + 1,
157173
)
158174
try:
159-
async with self.session.request(
175+
async with session.request(
160176
method,
161177
request_url,
162178
headers=self.headers,

pydepsdev/utils.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
SUPPORTED_SYSTEMS_DEPENDENTS,
2525
SUPPORTED_SYSTEMS_CAPABILITIES,
2626
SUPPORTED_SYSTEMS_QUERY,
27+
SUPPORTED_HASHES,
2728
)
2829

2930

0 commit comments

Comments
 (0)