30
30
31
31
class AlephHttpClient (AlephClient ):
32
32
api_server : str
33
- http_session : aiohttp .ClientSession
33
+ _http_session : Optional [ aiohttp .ClientSession ]
34
34
35
35
def __init__ (
36
36
self ,
@@ -48,35 +48,50 @@ def __init__(
48
48
if not self .api_server :
49
49
raise ValueError ("Missing API host" )
50
50
51
- connector : Union [aiohttp .BaseConnector , None ]
51
+ self . connector : Union [aiohttp .BaseConnector , None ]
52
52
unix_socket_path = api_unix_socket or settings .API_UNIX_SOCKET
53
+
53
54
if ssl_context :
54
- connector = aiohttp .TCPConnector (ssl = ssl_context )
55
+ self . connector = aiohttp .TCPConnector (ssl = ssl_context )
55
56
elif unix_socket_path and allow_unix_sockets :
56
57
check_unix_socket_valid (unix_socket_path )
57
- connector = aiohttp .UnixConnector (path = unix_socket_path )
58
+ self . connector = aiohttp .UnixConnector (path = unix_socket_path )
58
59
else :
59
- connector = None
60
-
61
- # ClientSession timeout defaults to a private sentinel object and may not be None.
62
- self .http_session = (
63
- aiohttp .ClientSession (
64
- base_url = self .api_server ,
65
- connector = connector ,
66
- timeout = timeout ,
67
- json_serialize = extended_json_encoder ,
68
- )
69
- if timeout
70
- else aiohttp .ClientSession (
71
- base_url = self .api_server ,
72
- connector = connector ,
73
- json_serialize = lambda obj : json .dumps (
74
- obj , default = extended_json_encoder
75
- ),
60
+ self .connector = None
61
+
62
+ self .timeout = timeout
63
+ self ._http_session = None
64
+
65
+ @property
66
+ def http_session (self ) -> aiohttp .ClientSession :
67
+ if self ._http_session is None :
68
+ raise Exception (
69
+ f"{ self .__class__ .__name__ } can only be using within an async context manager.\n \n "
70
+ "Please use it this way:\n \n "
71
+ " async with {self.__class__.__name__}(...) as client:"
76
72
)
77
- )
73
+
74
+ return self ._http_session
78
75
79
76
async def __aenter__ (self ) -> "AlephHttpClient" :
77
+ if self ._http_session is None :
78
+ self ._http_session = (
79
+ aiohttp .ClientSession (
80
+ base_url = self .api_server ,
81
+ connector = self .connector ,
82
+ timeout = self .timeout ,
83
+ json_serialize = extended_json_encoder ,
84
+ )
85
+ if self .timeout
86
+ else aiohttp .ClientSession (
87
+ base_url = self .api_server ,
88
+ connector = self .connector ,
89
+ json_serialize = lambda obj : json .dumps (
90
+ obj , default = extended_json_encoder
91
+ ),
92
+ )
93
+ )
94
+
80
95
return self
81
96
82
97
async def __aexit__ (self , exc_type , exc_val , exc_tb ):
0 commit comments