-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathasync_request.py
More file actions
303 lines (250 loc) · 9.4 KB
/
async_request.py
File metadata and controls
303 lines (250 loc) · 9.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import json
from io import BytesIO
from typing import Any, AsyncGenerator, Dict, Generic, List, TypedDict, Union, cast
import aiohttp
from typing_extensions import Literal, TypeVar
from .exceptions import NoContentError, raise_for_code_and_type
RequestVerb = Literal["get", "post", "put", "patch", "delete"]
T = TypeVar("T")
class AsyncRequestConfig(TypedDict):
base_url: str
api_key: str
headers: Union[Dict[str, str], None]
class AsyncRequest(Generic[T]):
def __init__(
self,
config: AsyncRequestConfig,
path: str,
params: Union[Dict[Any, Any], List[Dict[Any, Any]]],
verb: RequestVerb,
data: Union[bytes, None] = None,
stream: Union[bool, None] = False,
files: Union[Dict[str, Any], None] = None, # Add files parameter
):
self.path = path
self.params = params
self.verb = verb
self.base_url = config.get("base_url")
self.api_key = config.get("api_key")
self.data = data
self.headers = config.get("headers", None) or {"Content-Type": "application/json"}
self.stream = stream
self.files = files # Store files for multipart requests
def __convert_params(
self, params: Union[Dict[Any, Any], List[Dict[Any, Any]]]
) -> Dict[str, str]:
"""
Convert parameters to string values for URL encoding.
"""
if params is None:
return {}
if isinstance(params, str):
return params
if isinstance(params, list):
return {} # List params are only used in JSON body
converted = {}
for key, value in params.items():
if isinstance(value, bool):
converted[key] = str(value).lower()
else:
converted[key] = str(value)
return converted
async def perform(self) -> Union[T, None]:
"""
Async method to make an HTTP request to the JigsawStack API.
"""
async with self.__get_session() as session:
resp = await self.make_request(session, url=f"{self.base_url}{self.path}")
# For binary responses
if resp.status == 200:
content_type = resp.headers.get("content-type", "")
if not resp.text or any(
t in content_type
for t in [
"audio/",
"image/",
"application/octet-stream",
"image/png",
]
):
content = await resp.read()
return cast(T, content)
# For error responses
if resp.status != 200:
try:
error = await resp.json()
raise_for_code_and_type(
code=resp.status,
message=error.get("message"),
err=error.get("error"),
)
except json.JSONDecodeError:
raise_for_code_and_type(
code=500,
message="Failed to parse response. Invalid content type or encoding.",
)
# For JSON responses
try:
return cast(T, await resp.json())
except json.JSONDecodeError:
content = await resp.read()
return cast(T, content)
async def perform_file(self) -> Union[T, None]:
async with self.__get_session() as session:
resp = await self.make_request(session, url=f"{self.base_url}{self.path}")
if resp.status != 200:
try:
error = await resp.json()
raise_for_code_and_type(
code=resp.status,
message=error.get("message"),
err=error.get("error"),
)
except json.JSONDecodeError:
raise_for_code_and_type(
code=500,
message="Failed to parse response. Invalid content type or encoding.",
)
# For binary responses
if resp.status == 200:
content_type = resp.headers.get("content-type", "")
if "application/json" not in content_type:
content = await resp.read()
return cast(T, content)
return cast(T, await resp.json())
async def perform_with_content(self) -> T:
"""
Perform an async HTTP request and return the response content.
Returns:
T: The content of the response
Raises:
NoContentError: If the response content is `None`.
"""
resp = await self.perform()
if resp is None:
raise NoContentError()
return resp
async def perform_with_content_file(self) -> Union[aiohttp.ClientResponse, None]:
"""
Perform an async HTTP request and return the raw response.
Returns:
Union[aiohttp.ClientResponse, None]: The raw response
Raises:
NoContentError: If the response content is `None`.
"""
resp = await self.perform_file()
if resp is None:
raise NoContentError()
return resp
def __get_headers(self) -> Dict[str, str]:
"""
Prepare HTTP headers for the request.
Returns:
Dict[str, str]: Configured HTTP Headers
"""
h = {
"Accept": "application/json",
"x-api-key": f"{self.api_key}",
}
# only add Content-Type if not using multipart (files)
if not self.files and not self.data:
h["Content-Type"] = "application/json"
_headers = h.copy()
# don't override Content-Type if using multipart
if self.files and "Content-Type" in self.headers:
self.headers.pop("Content-Type")
_headers.update(self.headers)
return _headers
async def perform_streaming(self) -> AsyncGenerator[Union[T, str], None]:
"""
Async method to stream response from JigsawStack API.
Returns:
AsyncGenerator[Union[T, str], None]: A generator of response chunks
"""
async with self.__get_session() as session:
resp = await self.make_request(session, url=f"{self.base_url}{self.path}")
# delete calls do not return a body
if await resp.text() == "":
return
if resp.status != 200:
error = await resp.json()
raise_for_code_and_type(
code=resp.status,
message=error.get("message"),
err=error.get("error"),
)
async for chunk in resp.content.iter_chunked(1024): # 1KB chunks
if chunk:
yield await self.__try_parse_data(chunk)
async def perform_with_content_streaming(
self,
) -> AsyncGenerator[Union[T, str], None]:
"""
Perform an async HTTP request and return the response content as a streaming response.
Returns:
AsyncGenerator[Union[T, str], None]: Streaming response content
Raises:
NoContentError: If the response content is `None`.
"""
resp = await self.perform_streaming()
if resp is None:
raise NoContentError()
return resp
async def make_request(
self, session: aiohttp.ClientSession, url: str
) -> aiohttp.ClientResponse:
headers = self.__get_headers()
params = self.params
verb = self.verb
data = self.data
files = self.files
_params = None
_json = None
_data = None
_form_data = None
if verb.lower() in ["get", "delete"]:
_params = self.__convert_params(params)
elif files:
_form_data = aiohttp.FormData()
_form_data.add_field("file", BytesIO(files["file"]), filename="upload")
if params and isinstance(params, dict):
_form_data.add_field("body", json.dumps(params), content_type="application/json")
headers.pop("Content-Type", None)
elif data: # raw data request
_data = data
else: # pure JSON request
_json = params
return await session.request(
verb,
url,
params=_params,
json=_json,
data=_form_data or _data,
headers=headers,
)
def __get_session(self) -> aiohttp.ClientSession:
"""
Create and return an async client session.
Returns:
aiohttp.ClientSession: An async client session
"""
return aiohttp.ClientSession()
@staticmethod
async def __try_parse_data(chunk: bytes) -> Union[T, str]:
"""
Attempt to parse a chunk of data as JSON or return as text.
Args:
chunk (bytes): The data chunk to parse
Returns:
Union[T, str]: Parsed JSON or raw text
"""
if not chunk:
return chunk
# Decode bytes to text
text = chunk.decode("utf-8")
try:
# Try to parse as JSON
return json.loads(text)
except json.JSONDecodeError:
# Return as text if not valid JSON
return text