22
33import enum
44import json
5- from typing import IO , Any , AsyncIterator , Dict , List , Optional , Tuple , TypeVar , cast
5+ from collections .abc import AsyncIterator
6+ from typing import IO , Any , Optional , TypeVar , cast
67from uuid import uuid4
78
89import httpx
2021try :
2122 from websockets .client import ( # type: ignore[import-not-found,unused-ignore]
2223 WebSocketClientProtocol ,
24+ )
25+ from websockets .client import (
2326 connect as ws_connect ,
2427 )
2528 from websockets .typing import ( # type: ignore[import-not-found,unused-ignore]
@@ -63,18 +66,16 @@ class AsyncBaseClient:
6366 def __init__ (
6467 self ,
6568 url : str = "" ,
66- headers : Optional [Dict [str , str ]] = None ,
69+ headers : Optional [dict [str , str ]] = None ,
6770 http_client : Optional [httpx .AsyncClient ] = None ,
6871 ws_url : str = "" ,
69- ws_headers : Optional [Dict [str , Any ]] = None ,
72+ ws_headers : Optional [dict [str , Any ]] = None ,
7073 ws_origin : Optional [str ] = None ,
71- ws_connection_init_payload : Optional [Dict [str , Any ]] = None ,
74+ ws_connection_init_payload : Optional [dict [str , Any ]] = None ,
7275 ) -> None :
7376 self .url = url
7477 self .headers = headers
75- self .http_client = (
76- http_client if http_client else httpx .AsyncClient (headers = headers )
77- )
78+ self .http_client = http_client if http_client else httpx .AsyncClient (headers = headers )
7879
7980 self .ws_url = ws_url
8081 self .ws_headers = ws_headers or {}
@@ -96,7 +97,7 @@ async def execute(
9697 self ,
9798 query : str ,
9899 operation_name : Optional [str ] = None ,
99- variables : Optional [Dict [str , Any ]] = None ,
100+ variables : Optional [dict [str , Any ]] = None ,
100101 ** kwargs : Any ,
101102 ) -> httpx .Response :
102103 processed_variables , files , files_map = self ._process_variables (variables )
@@ -118,43 +119,37 @@ async def execute(
118119 ** kwargs ,
119120 )
120121
121- def get_data (self , response : httpx .Response ) -> Dict [str , Any ]:
122+ def get_data (self , response : httpx .Response ) -> dict [str , Any ]:
122123 if not response .is_success :
123- raise GraphQLClientHttpError (
124- status_code = response .status_code , response = response
125- )
124+ raise GraphQLClientHttpError (status_code = response .status_code , response = response )
126125
127126 try :
128127 response_json = response .json ()
129128 except ValueError as exc :
130129 raise GraphQLClientInvalidResponseError (response = response ) from exc
131130
132- if (not isinstance (response_json , dict )) or (
133- "data" not in response_json and "errors" not in response_json
134- ):
131+ if (not isinstance (response_json , dict )) or ("data" not in response_json and "errors" not in response_json ):
135132 raise GraphQLClientInvalidResponseError (response = response )
136133
137134 data = response_json .get ("data" )
138135 errors = response_json .get ("errors" )
139136
140137 if errors :
141- raise GraphQLClientGraphQLMultiError .from_errors_dicts (
142- errors_dicts = errors , data = data
143- )
138+ raise GraphQLClientGraphQLMultiError .from_errors_dicts (errors_dicts = errors , data = data )
144139
145- return cast (Dict [str , Any ], data )
140+ return cast (dict [str , Any ], data )
146141
147142 async def execute_ws (
148143 self ,
149144 query : str ,
150145 operation_name : Optional [str ] = None ,
151- variables : Optional [Dict [str , Any ]] = None ,
146+ variables : Optional [dict [str , Any ]] = None ,
152147 ** kwargs : Any ,
153- ) -> AsyncIterator [Dict [str , Any ]]:
148+ ) -> AsyncIterator [dict [str , Any ]]:
154149 headers = self .ws_headers .copy ()
155150 headers .update (kwargs .get ("extra_headers" , {}))
156151
157- merged_kwargs : Dict [str , Any ] = {"origin" : self .ws_origin }
152+ merged_kwargs : dict [str , Any ] = {"origin" : self .ws_origin }
158153 merged_kwargs .update (kwargs )
159154 merged_kwargs ["extra_headers" ] = headers
160155
@@ -185,24 +180,16 @@ async def execute_ws(
185180 yield data
186181
187182 def _process_variables (
188- self , variables : Optional [Dict [str , Any ]]
189- ) -> Tuple [
190- Dict [str , Any ], Dict [str , Tuple [str , IO [bytes ], str ]], Dict [str , List [str ]]
191- ]:
183+ self , variables : Optional [dict [str , Any ]]
184+ ) -> tuple [dict [str , Any ], dict [str , tuple [str , IO [bytes ], str ]], dict [str , list [str ]]]:
192185 if not variables :
193186 return {}, {}, {}
194187
195188 serializable_variables = self ._convert_dict_to_json_serializable (variables )
196189 return self ._get_files_from_variables (serializable_variables )
197190
198- def _convert_dict_to_json_serializable (
199- self , dict_ : Dict [str , Any ]
200- ) -> Dict [str , Any ]:
201- return {
202- key : self ._convert_value (value )
203- for key , value in dict_ .items ()
204- if value is not UNSET
205- }
191+ def _convert_dict_to_json_serializable (self , dict_ : dict [str , Any ]) -> dict [str , Any ]:
192+ return {key : self ._convert_value (value ) for key , value in dict_ .items () if value is not UNSET }
206193
207194 def _convert_value (self , value : Any ) -> Any :
208195 if isinstance (value , BaseModel ):
@@ -212,12 +199,10 @@ def _convert_value(self, value: Any) -> Any:
212199 return value
213200
214201 def _get_files_from_variables (
215- self , variables : Dict [str , Any ]
216- ) -> Tuple [
217- Dict [str , Any ], Dict [str , Tuple [str , IO [bytes ], str ]], Dict [str , List [str ]]
218- ]:
219- files_map : Dict [str , List [str ]] = {}
220- files_list : List [Upload ] = []
202+ self , variables : dict [str , Any ]
203+ ) -> tuple [dict [str , Any ], dict [str , tuple [str , IO [bytes ], str ]], dict [str , list [str ]]]:
204+ files_map : dict [str , list [str ]] = {}
205+ files_list : list [Upload ] = []
221206
222207 def separate_files (path : str , obj : Any ) -> Any :
223208 if isinstance (obj , list ):
@@ -247,7 +232,7 @@ def separate_files(path: str, obj: Any) -> Any:
247232 return obj
248233
249234 nulled_variables = separate_files ("variables" , variables )
250- files : Dict [str , Tuple [str , IO [bytes ], str ]] = {
235+ files : dict [str , tuple [str , IO [bytes ], str ]] = {
251236 str (i ): (file_ .filename , cast (IO [bytes ], file_ .content ), file_ .content_type )
252237 for i , file_ in enumerate (files_list )
253238 }
@@ -257,9 +242,9 @@ async def _execute_multipart(
257242 self ,
258243 query : str ,
259244 operation_name : Optional [str ],
260- variables : Dict [str , Any ],
261- files : Dict [str , Tuple [str , IO [bytes ], str ]],
262- files_map : Dict [str , List [str ]],
245+ variables : dict [str , Any ],
246+ files : dict [str , tuple [str , IO [bytes ], str ]],
247+ files_map : dict [str , list [str ]],
263248 ** kwargs : Any ,
264249 ) -> httpx .Response :
265250 data = {
@@ -274,21 +259,19 @@ async def _execute_multipart(
274259 "map" : json .dumps (files_map , default = to_jsonable_python ),
275260 }
276261
277- return await self .http_client .post (
278- url = self .url , data = data , files = files , ** kwargs
279- )
262+ return await self .http_client .post (url = self .url , data = data , files = files , ** kwargs )
280263
281264 async def _execute_json (
282265 self ,
283266 query : str ,
284267 operation_name : Optional [str ],
285- variables : Dict [str , Any ],
268+ variables : dict [str , Any ],
286269 ** kwargs : Any ,
287270 ) -> httpx .Response :
288- headers : Dict [str , str ] = {"Content-Type" : "application/json" }
271+ headers : dict [str , str ] = {"Content-Type" : "application/json" }
289272 headers .update (kwargs .get ("headers" , {}))
290273
291- merged_kwargs : Dict [str , Any ] = kwargs .copy ()
274+ merged_kwargs : dict [str , Any ] = kwargs .copy ()
292275 merged_kwargs ["headers" ] = headers
293276
294277 return await self .http_client .post (
@@ -305,9 +288,7 @@ async def _execute_json(
305288 )
306289
307290 async def _send_connection_init (self , websocket : WebSocketClientProtocol ) -> None :
308- payload : Dict [str , Any ] = {
309- "type" : GraphQLTransportWSMessageType .CONNECTION_INIT .value
310- }
291+ payload : dict [str , Any ] = {"type" : GraphQLTransportWSMessageType .CONNECTION_INIT .value }
311292 if self .ws_connection_init_payload :
312293 payload ["payload" ] = self .ws_connection_init_payload
313294 await websocket .send (json .dumps (payload ))
@@ -318,25 +299,23 @@ async def _send_subscribe(
318299 operation_id : str ,
319300 query : str ,
320301 operation_name : Optional [str ] = None ,
321- variables : Optional [Dict [str , Any ]] = None ,
302+ variables : Optional [dict [str , Any ]] = None ,
322303 ) -> None :
323- payload : Dict [str , Any ] = {
304+ payload : dict [str , Any ] = {
324305 "id" : operation_id ,
325306 "type" : GraphQLTransportWSMessageType .SUBSCRIBE .value ,
326307 "payload" : {"query" : query , "operationName" : operation_name },
327308 }
328309 if variables :
329- payload ["payload" ]["variables" ] = self ._convert_dict_to_json_serializable (
330- variables
331- )
310+ payload ["payload" ]["variables" ] = self ._convert_dict_to_json_serializable (variables )
332311 await websocket .send (json .dumps (payload ))
333312
334313 async def _handle_ws_message (
335314 self ,
336315 message : Data ,
337316 websocket : WebSocketClientProtocol ,
338317 expected_type : Optional [GraphQLTransportWSMessageType ] = None ,
339- ) -> Optional [Dict [str , Any ]]:
318+ ) -> Optional [dict [str , Any ]]:
340319 try :
341320 message_dict = json .loads (message )
342321 except json .JSONDecodeError as exc :
@@ -349,24 +328,18 @@ async def _handle_ws_message(
349328 raise GraphQLClientInvalidMessageFormat (message = message )
350329
351330 if expected_type and expected_type != type_ :
352- raise GraphQLClientInvalidMessageFormat (
353- f"Invalid message received. Expected: { expected_type .value } "
354- )
331+ raise GraphQLClientInvalidMessageFormat (f"Invalid message received. Expected: { expected_type .value } " )
355332
356333 if type_ == GraphQLTransportWSMessageType .NEXT :
357334 if "data" not in payload :
358335 raise GraphQLClientInvalidMessageFormat (message = message )
359- return cast (Dict [str , Any ], payload ["data" ])
336+ return cast (dict [str , Any ], payload ["data" ])
360337
361338 if type_ == GraphQLTransportWSMessageType .COMPLETE :
362339 await websocket .close ()
363340 elif type_ == GraphQLTransportWSMessageType .PING :
364- await websocket .send (
365- json .dumps ({"type" : GraphQLTransportWSMessageType .PONG .value })
366- )
341+ await websocket .send (json .dumps ({"type" : GraphQLTransportWSMessageType .PONG .value }))
367342 elif type_ == GraphQLTransportWSMessageType .ERROR :
368- raise GraphQLClientGraphQLMultiError .from_errors_dicts (
369- errors_dicts = payload , data = message_dict
370- )
343+ raise GraphQLClientGraphQLMultiError .from_errors_dicts (errors_dicts = payload , data = message_dict )
371344
372345 return None
0 commit comments