4848
4949
5050class 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 ,
0 commit comments