linq-python 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. linq/__init__.py +102 -0
  2. linq/_base_client.py +2149 -0
  3. linq/_client.py +2479 -0
  4. linq/_compat.py +226 -0
  5. linq/_constants.py +14 -0
  6. linq/_exceptions.py +108 -0
  7. linq/_files.py +123 -0
  8. linq/_models.py +878 -0
  9. linq/_qs.py +153 -0
  10. linq/_resource.py +43 -0
  11. linq/_response.py +833 -0
  12. linq/_streaming.py +338 -0
  13. linq/_types.py +271 -0
  14. linq/_utils/__init__.py +65 -0
  15. linq/_utils/_compat.py +45 -0
  16. linq/_utils/_datetime_parse.py +136 -0
  17. linq/_utils/_json.py +35 -0
  18. linq/_utils/_logs.py +25 -0
  19. linq/_utils/_path.py +127 -0
  20. linq/_utils/_proxy.py +65 -0
  21. linq/_utils/_reflection.py +42 -0
  22. linq/_utils/_resources_proxy.py +24 -0
  23. linq/_utils/_streams.py +12 -0
  24. linq/_utils/_sync.py +58 -0
  25. linq/_utils/_transform.py +457 -0
  26. linq/_utils/_typing.py +156 -0
  27. linq/_utils/_utils.py +421 -0
  28. linq/_version.py +4 -0
  29. linq/lib/.keep +4 -0
  30. linq/pagination.py +95 -0
  31. linq/py.typed +0 -0
  32. linq/resources/__init__.py +134 -0
  33. linq/resources/attachments.py +589 -0
  34. linq/resources/capability.py +297 -0
  35. linq/resources/chats/__init__.py +61 -0
  36. linq/resources/chats/chats.py +1492 -0
  37. linq/resources/chats/messages.py +416 -0
  38. linq/resources/chats/participants.py +322 -0
  39. linq/resources/chats/typing.py +299 -0
  40. linq/resources/contact_card.py +472 -0
  41. linq/resources/messages.py +686 -0
  42. linq/resources/phone_numbers.py +163 -0
  43. linq/resources/phonenumbers.py +165 -0
  44. linq/resources/webhook_events.py +319 -0
  45. linq/resources/webhook_subscriptions.py +776 -0
  46. linq/resources/webhooks.py +34 -0
  47. linq/types/__init__.py +90 -0
  48. linq/types/attachment_create_params.py +42 -0
  49. linq/types/attachment_create_response.py +44 -0
  50. linq/types/attachment_retrieve_response.py +55 -0
  51. linq/types/capability_check_RCS_params.py +20 -0
  52. linq/types/capability_check_i_message_params.py +20 -0
  53. linq/types/chat.py +44 -0
  54. linq/types/chat_create_params.py +33 -0
  55. linq/types/chat_create_response.py +44 -0
  56. linq/types/chat_created_webhook_event.py +87 -0
  57. linq/types/chat_group_icon_update_failed_webhook_event.py +65 -0
  58. linq/types/chat_group_icon_updated_webhook_event.py +66 -0
  59. linq/types/chat_group_name_update_failed_webhook_event.py +65 -0
  60. linq/types/chat_group_name_updated_webhook_event.py +66 -0
  61. linq/types/chat_leave_chat_response.py +15 -0
  62. linq/types/chat_list_chats_params.py +36 -0
  63. linq/types/chat_send_voicememo_params.py +23 -0
  64. linq/types/chat_send_voicememo_response.py +79 -0
  65. linq/types/chat_typing_indicator_started_webhook_event.py +52 -0
  66. linq/types/chat_typing_indicator_stopped_webhook_event.py +52 -0
  67. linq/types/chat_update_params.py +15 -0
  68. linq/types/chat_update_response.py +13 -0
  69. linq/types/chats/__init__.py +12 -0
  70. linq/types/chats/message_list_params.py +15 -0
  71. linq/types/chats/message_send_params.py +18 -0
  72. linq/types/chats/message_send_response.py +16 -0
  73. linq/types/chats/participant_add_params.py +12 -0
  74. linq/types/chats/participant_add_response.py +15 -0
  75. linq/types/chats/participant_remove_params.py +12 -0
  76. linq/types/chats/participant_remove_response.py +15 -0
  77. linq/types/chats/sent_message.py +69 -0
  78. linq/types/contact_card_create_params.py +24 -0
  79. linq/types/contact_card_retrieve_params.py +15 -0
  80. linq/types/contact_card_retrieve_response.py +23 -0
  81. linq/types/contact_card_update_params.py +21 -0
  82. linq/types/events_webhook_event.py +50 -0
  83. linq/types/handle_check_response.py +13 -0
  84. linq/types/link_part_param.py +22 -0
  85. linq/types/media_part_param.py +54 -0
  86. linq/types/message.py +87 -0
  87. linq/types/message_add_reaction_params.py +32 -0
  88. linq/types/message_add_reaction_response.py +15 -0
  89. linq/types/message_content_param.py +82 -0
  90. linq/types/message_delivered_webhook_event.py +65 -0
  91. linq/types/message_edited_webhook_event.py +100 -0
  92. linq/types/message_effect.py +23 -0
  93. linq/types/message_effect_param.py +22 -0
  94. linq/types/message_event_v2.py +116 -0
  95. linq/types/message_failed_webhook_event.py +72 -0
  96. linq/types/message_list_messages_thread_params.py +18 -0
  97. linq/types/message_read_webhook_event.py +65 -0
  98. linq/types/message_received_webhook_event.py +65 -0
  99. linq/types/message_sent_webhook_event.py +65 -0
  100. linq/types/message_update_params.py +15 -0
  101. linq/types/participant_added_webhook_event.py +66 -0
  102. linq/types/participant_removed_webhook_event.py +66 -0
  103. linq/types/phone_number_list_response.py +20 -0
  104. linq/types/phone_number_status_updated_webhook_event.py +82 -0
  105. linq/types/phonenumber_list_response.py +39 -0
  106. linq/types/reaction_added_webhook_event.py +46 -0
  107. linq/types/reaction_event_base.py +85 -0
  108. linq/types/reaction_removed_webhook_event.py +46 -0
  109. linq/types/reply_to.py +21 -0
  110. linq/types/reply_to_param.py +21 -0
  111. linq/types/schemas_media_part_response.py +29 -0
  112. linq/types/schemas_message_effect.py +18 -0
  113. linq/types/schemas_text_part_response.py +22 -0
  114. linq/types/set_contact_card.py +24 -0
  115. linq/types/shared/__init__.py +9 -0
  116. linq/types/shared/chat_handle.py +33 -0
  117. linq/types/shared/media_part_response.py +34 -0
  118. linq/types/shared/reaction.py +56 -0
  119. linq/types/shared/reaction_type.py +7 -0
  120. linq/types/shared/service_type.py +7 -0
  121. linq/types/shared/text_decoration.py +23 -0
  122. linq/types/shared/text_part_response.py +26 -0
  123. linq/types/shared_params/__init__.py +5 -0
  124. linq/types/shared_params/reaction_type.py +9 -0
  125. linq/types/shared_params/service_type.py +9 -0
  126. linq/types/shared_params/text_decoration.py +23 -0
  127. linq/types/supported_content_type.py +60 -0
  128. linq/types/text_part_param.py +44 -0
  129. linq/types/webhook_event_list_response.py +17 -0
  130. linq/types/webhook_event_type.py +33 -0
  131. linq/types/webhook_subscription.py +35 -0
  132. linq/types/webhook_subscription_create_params.py +27 -0
  133. linq/types/webhook_subscription_create_response.py +46 -0
  134. linq/types/webhook_subscription_list_response.py +13 -0
  135. linq/types/webhook_subscription_update_params.py +30 -0
  136. linq_python-0.1.0.dist-info/METADATA +572 -0
  137. linq_python-0.1.0.dist-info/RECORD +139 -0
  138. linq_python-0.1.0.dist-info/WHEEL +4 -0
  139. linq_python-0.1.0.dist-info/licenses/LICENSE +201 -0
linq/_response.py ADDED
@@ -0,0 +1,833 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import inspect
5
+ import logging
6
+ import datetime
7
+ import functools
8
+ from types import TracebackType
9
+ from typing import (
10
+ TYPE_CHECKING,
11
+ Any,
12
+ Union,
13
+ Generic,
14
+ TypeVar,
15
+ Callable,
16
+ Iterator,
17
+ AsyncIterator,
18
+ cast,
19
+ overload,
20
+ )
21
+ from typing_extensions import Awaitable, ParamSpec, override, get_origin
22
+
23
+ import anyio
24
+ import httpx
25
+ import pydantic
26
+
27
+ from ._types import NoneType
28
+ from ._utils import is_given, extract_type_arg, is_annotated_type, is_type_alias_type, extract_type_var_from_base
29
+ from ._models import BaseModel, is_basemodel
30
+ from ._constants import RAW_RESPONSE_HEADER, OVERRIDE_CAST_TO_HEADER
31
+ from ._streaming import Stream, AsyncStream, is_stream_class_type, extract_stream_chunk_type
32
+ from ._exceptions import LinqApiv3Error, APIResponseValidationError
33
+
34
+ if TYPE_CHECKING:
35
+ from ._models import FinalRequestOptions
36
+ from ._base_client import BaseClient
37
+
38
+
39
+ P = ParamSpec("P")
40
+ R = TypeVar("R")
41
+ _T = TypeVar("_T")
42
+ _APIResponseT = TypeVar("_APIResponseT", bound="APIResponse[Any]")
43
+ _AsyncAPIResponseT = TypeVar("_AsyncAPIResponseT", bound="AsyncAPIResponse[Any]")
44
+
45
+ log: logging.Logger = logging.getLogger(__name__)
46
+
47
+
48
+ class BaseAPIResponse(Generic[R]):
49
+ _cast_to: type[R]
50
+ _client: BaseClient[Any, Any]
51
+ _parsed_by_type: dict[type[Any], Any]
52
+ _is_sse_stream: bool
53
+ _stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None
54
+ _options: FinalRequestOptions
55
+
56
+ http_response: httpx.Response
57
+
58
+ retries_taken: int
59
+ """The number of retries made. If no retries happened this will be `0`"""
60
+
61
+ def __init__(
62
+ self,
63
+ *,
64
+ raw: httpx.Response,
65
+ cast_to: type[R],
66
+ client: BaseClient[Any, Any],
67
+ stream: bool,
68
+ stream_cls: type[Stream[Any]] | type[AsyncStream[Any]] | None,
69
+ options: FinalRequestOptions,
70
+ retries_taken: int = 0,
71
+ ) -> None:
72
+ self._cast_to = cast_to
73
+ self._client = client
74
+ self._parsed_by_type = {}
75
+ self._is_sse_stream = stream
76
+ self._stream_cls = stream_cls
77
+ self._options = options
78
+ self.http_response = raw
79
+ self.retries_taken = retries_taken
80
+
81
+ @property
82
+ def headers(self) -> httpx.Headers:
83
+ return self.http_response.headers
84
+
85
+ @property
86
+ def http_request(self) -> httpx.Request:
87
+ """Returns the httpx Request instance associated with the current response."""
88
+ return self.http_response.request
89
+
90
+ @property
91
+ def status_code(self) -> int:
92
+ return self.http_response.status_code
93
+
94
+ @property
95
+ def url(self) -> httpx.URL:
96
+ """Returns the URL for which the request was made."""
97
+ return self.http_response.url
98
+
99
+ @property
100
+ def method(self) -> str:
101
+ return self.http_request.method
102
+
103
+ @property
104
+ def http_version(self) -> str:
105
+ return self.http_response.http_version
106
+
107
+ @property
108
+ def elapsed(self) -> datetime.timedelta:
109
+ """The time taken for the complete request/response cycle to complete."""
110
+ return self.http_response.elapsed
111
+
112
+ @property
113
+ def is_closed(self) -> bool:
114
+ """Whether or not the response body has been closed.
115
+
116
+ If this is False then there is response data that has not been read yet.
117
+ You must either fully consume the response body or call `.close()`
118
+ before discarding the response to prevent resource leaks.
119
+ """
120
+ return self.http_response.is_closed
121
+
122
+ @override
123
+ def __repr__(self) -> str:
124
+ return (
125
+ f"<{self.__class__.__name__} [{self.status_code} {self.http_response.reason_phrase}] type={self._cast_to}>"
126
+ )
127
+
128
+ def _parse(self, *, to: type[_T] | None = None) -> R | _T:
129
+ cast_to = to if to is not None else self._cast_to
130
+
131
+ # unwrap `TypeAlias('Name', T)` -> `T`
132
+ if is_type_alias_type(cast_to):
133
+ cast_to = cast_to.__value__ # type: ignore[unreachable]
134
+
135
+ # unwrap `Annotated[T, ...]` -> `T`
136
+ if cast_to and is_annotated_type(cast_to):
137
+ cast_to = extract_type_arg(cast_to, 0)
138
+
139
+ origin = get_origin(cast_to) or cast_to
140
+
141
+ if self._is_sse_stream:
142
+ if to:
143
+ if not is_stream_class_type(to):
144
+ raise TypeError(f"Expected custom parse type to be a subclass of {Stream} or {AsyncStream}")
145
+
146
+ return cast(
147
+ _T,
148
+ to(
149
+ cast_to=extract_stream_chunk_type(
150
+ to,
151
+ failure_message="Expected custom stream type to be passed with a type argument, e.g. Stream[ChunkType]",
152
+ ),
153
+ response=self.http_response,
154
+ client=cast(Any, self._client),
155
+ options=self._options,
156
+ ),
157
+ )
158
+
159
+ if self._stream_cls:
160
+ return cast(
161
+ R,
162
+ self._stream_cls(
163
+ cast_to=extract_stream_chunk_type(self._stream_cls),
164
+ response=self.http_response,
165
+ client=cast(Any, self._client),
166
+ options=self._options,
167
+ ),
168
+ )
169
+
170
+ stream_cls = cast("type[Stream[Any]] | type[AsyncStream[Any]] | None", self._client._default_stream_cls)
171
+ if stream_cls is None:
172
+ raise MissingStreamClassError()
173
+
174
+ return cast(
175
+ R,
176
+ stream_cls(
177
+ cast_to=cast_to,
178
+ response=self.http_response,
179
+ client=cast(Any, self._client),
180
+ options=self._options,
181
+ ),
182
+ )
183
+
184
+ if cast_to is NoneType:
185
+ return cast(R, None)
186
+
187
+ response = self.http_response
188
+ if cast_to == str:
189
+ return cast(R, response.text)
190
+
191
+ if cast_to == bytes:
192
+ return cast(R, response.content)
193
+
194
+ if cast_to == int:
195
+ return cast(R, int(response.text))
196
+
197
+ if cast_to == float:
198
+ return cast(R, float(response.text))
199
+
200
+ if cast_to == bool:
201
+ return cast(R, response.text.lower() == "true")
202
+
203
+ if origin == APIResponse:
204
+ raise RuntimeError("Unexpected state - cast_to is `APIResponse`")
205
+
206
+ if inspect.isclass(origin) and issubclass(origin, httpx.Response):
207
+ # Because of the invariance of our ResponseT TypeVar, users can subclass httpx.Response
208
+ # and pass that class to our request functions. We cannot change the variance to be either
209
+ # covariant or contravariant as that makes our usage of ResponseT illegal. We could construct
210
+ # the response class ourselves but that is something that should be supported directly in httpx
211
+ # as it would be easy to incorrectly construct the Response object due to the multitude of arguments.
212
+ if cast_to != httpx.Response:
213
+ raise ValueError(f"Subclasses of httpx.Response cannot be passed to `cast_to`")
214
+ return cast(R, response)
215
+
216
+ if (
217
+ inspect.isclass(
218
+ origin # pyright: ignore[reportUnknownArgumentType]
219
+ )
220
+ and not issubclass(origin, BaseModel)
221
+ and issubclass(origin, pydantic.BaseModel)
222
+ ):
223
+ raise TypeError("Pydantic models must subclass our base model type, e.g. `from linq import BaseModel`")
224
+
225
+ if (
226
+ cast_to is not object
227
+ and not origin is list
228
+ and not origin is dict
229
+ and not origin is Union
230
+ and not issubclass(origin, BaseModel)
231
+ ):
232
+ raise RuntimeError(
233
+ f"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx.Response}."
234
+ )
235
+
236
+ # split is required to handle cases where additional information is included
237
+ # in the response, e.g. application/json; charset=utf-8
238
+ content_type, *_ = response.headers.get("content-type", "*").split(";")
239
+ if not content_type.endswith("json"):
240
+ if is_basemodel(cast_to):
241
+ try:
242
+ data = response.json()
243
+ except Exception as exc:
244
+ log.debug("Could not read JSON from response data due to %s - %s", type(exc), exc)
245
+ else:
246
+ return self._client._process_response_data(
247
+ data=data,
248
+ cast_to=cast_to, # type: ignore
249
+ response=response,
250
+ )
251
+
252
+ if self._client._strict_response_validation:
253
+ raise APIResponseValidationError(
254
+ response=response,
255
+ message=f"Expected Content-Type response header to be `application/json` but received `{content_type}` instead.",
256
+ body=response.text,
257
+ )
258
+
259
+ # If the API responds with content that isn't JSON then we just return
260
+ # the (decoded) text without performing any parsing so that you can still
261
+ # handle the response however you need to.
262
+ return response.text # type: ignore
263
+
264
+ data = response.json()
265
+
266
+ return self._client._process_response_data(
267
+ data=data,
268
+ cast_to=cast_to, # type: ignore
269
+ response=response,
270
+ )
271
+
272
+
273
+ class APIResponse(BaseAPIResponse[R]):
274
+ @overload
275
+ def parse(self, *, to: type[_T]) -> _T: ...
276
+
277
+ @overload
278
+ def parse(self) -> R: ...
279
+
280
+ def parse(self, *, to: type[_T] | None = None) -> R | _T:
281
+ """Returns the rich python representation of this response's data.
282
+
283
+ For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
284
+
285
+ You can customise the type that the response is parsed into through
286
+ the `to` argument, e.g.
287
+
288
+ ```py
289
+ from linq import BaseModel
290
+
291
+
292
+ class MyModel(BaseModel):
293
+ foo: str
294
+
295
+
296
+ obj = response.parse(to=MyModel)
297
+ print(obj.foo)
298
+ ```
299
+
300
+ We support parsing:
301
+ - `BaseModel`
302
+ - `dict`
303
+ - `list`
304
+ - `Union`
305
+ - `str`
306
+ - `int`
307
+ - `float`
308
+ - `httpx.Response`
309
+ """
310
+ cache_key = to if to is not None else self._cast_to
311
+ cached = self._parsed_by_type.get(cache_key)
312
+ if cached is not None:
313
+ return cached # type: ignore[no-any-return]
314
+
315
+ if not self._is_sse_stream:
316
+ self.read()
317
+
318
+ parsed = self._parse(to=to)
319
+ if is_given(self._options.post_parser):
320
+ parsed = self._options.post_parser(parsed)
321
+
322
+ self._parsed_by_type[cache_key] = parsed
323
+ return parsed
324
+
325
+ def read(self) -> bytes:
326
+ """Read and return the binary response content."""
327
+ try:
328
+ return self.http_response.read()
329
+ except httpx.StreamConsumed as exc:
330
+ # The default error raised by httpx isn't very
331
+ # helpful in our case so we re-raise it with
332
+ # a different error message.
333
+ raise StreamAlreadyConsumed() from exc
334
+
335
+ def text(self) -> str:
336
+ """Read and decode the response content into a string."""
337
+ self.read()
338
+ return self.http_response.text
339
+
340
+ def json(self) -> object:
341
+ """Read and decode the JSON response content."""
342
+ self.read()
343
+ return self.http_response.json()
344
+
345
+ def close(self) -> None:
346
+ """Close the response and release the connection.
347
+
348
+ Automatically called if the response body is read to completion.
349
+ """
350
+ self.http_response.close()
351
+
352
+ def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
353
+ """
354
+ A byte-iterator over the decoded response content.
355
+
356
+ This automatically handles gzip, deflate and brotli encoded responses.
357
+ """
358
+ for chunk in self.http_response.iter_bytes(chunk_size):
359
+ yield chunk
360
+
361
+ def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
362
+ """A str-iterator over the decoded response content
363
+ that handles both gzip, deflate, etc but also detects the content's
364
+ string encoding.
365
+ """
366
+ for chunk in self.http_response.iter_text(chunk_size):
367
+ yield chunk
368
+
369
+ def iter_lines(self) -> Iterator[str]:
370
+ """Like `iter_text()` but will only yield chunks for each line"""
371
+ for chunk in self.http_response.iter_lines():
372
+ yield chunk
373
+
374
+
375
+ class AsyncAPIResponse(BaseAPIResponse[R]):
376
+ @overload
377
+ async def parse(self, *, to: type[_T]) -> _T: ...
378
+
379
+ @overload
380
+ async def parse(self) -> R: ...
381
+
382
+ async def parse(self, *, to: type[_T] | None = None) -> R | _T:
383
+ """Returns the rich python representation of this response's data.
384
+
385
+ For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
386
+
387
+ You can customise the type that the response is parsed into through
388
+ the `to` argument, e.g.
389
+
390
+ ```py
391
+ from linq import BaseModel
392
+
393
+
394
+ class MyModel(BaseModel):
395
+ foo: str
396
+
397
+
398
+ obj = response.parse(to=MyModel)
399
+ print(obj.foo)
400
+ ```
401
+
402
+ We support parsing:
403
+ - `BaseModel`
404
+ - `dict`
405
+ - `list`
406
+ - `Union`
407
+ - `str`
408
+ - `httpx.Response`
409
+ """
410
+ cache_key = to if to is not None else self._cast_to
411
+ cached = self._parsed_by_type.get(cache_key)
412
+ if cached is not None:
413
+ return cached # type: ignore[no-any-return]
414
+
415
+ if not self._is_sse_stream:
416
+ await self.read()
417
+
418
+ parsed = self._parse(to=to)
419
+ if is_given(self._options.post_parser):
420
+ parsed = self._options.post_parser(parsed)
421
+
422
+ self._parsed_by_type[cache_key] = parsed
423
+ return parsed
424
+
425
+ async def read(self) -> bytes:
426
+ """Read and return the binary response content."""
427
+ try:
428
+ return await self.http_response.aread()
429
+ except httpx.StreamConsumed as exc:
430
+ # the default error raised by httpx isn't very
431
+ # helpful in our case so we re-raise it with
432
+ # a different error message
433
+ raise StreamAlreadyConsumed() from exc
434
+
435
+ async def text(self) -> str:
436
+ """Read and decode the response content into a string."""
437
+ await self.read()
438
+ return self.http_response.text
439
+
440
+ async def json(self) -> object:
441
+ """Read and decode the JSON response content."""
442
+ await self.read()
443
+ return self.http_response.json()
444
+
445
+ async def close(self) -> None:
446
+ """Close the response and release the connection.
447
+
448
+ Automatically called if the response body is read to completion.
449
+ """
450
+ await self.http_response.aclose()
451
+
452
+ async def iter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
453
+ """
454
+ A byte-iterator over the decoded response content.
455
+
456
+ This automatically handles gzip, deflate and brotli encoded responses.
457
+ """
458
+ async for chunk in self.http_response.aiter_bytes(chunk_size):
459
+ yield chunk
460
+
461
+ async def iter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]:
462
+ """A str-iterator over the decoded response content
463
+ that handles both gzip, deflate, etc but also detects the content's
464
+ string encoding.
465
+ """
466
+ async for chunk in self.http_response.aiter_text(chunk_size):
467
+ yield chunk
468
+
469
+ async def iter_lines(self) -> AsyncIterator[str]:
470
+ """Like `iter_text()` but will only yield chunks for each line"""
471
+ async for chunk in self.http_response.aiter_lines():
472
+ yield chunk
473
+
474
+
475
+ class BinaryAPIResponse(APIResponse[bytes]):
476
+ """Subclass of APIResponse providing helpers for dealing with binary data.
477
+
478
+ Note: If you want to stream the response data instead of eagerly reading it
479
+ all at once then you should use `.with_streaming_response` when making
480
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
481
+ """
482
+
483
+ def write_to_file(
484
+ self,
485
+ file: str | os.PathLike[str],
486
+ ) -> None:
487
+ """Write the output to the given file.
488
+
489
+ Accepts a filename or any path-like object, e.g. pathlib.Path
490
+
491
+ Note: if you want to stream the data to the file instead of writing
492
+ all at once then you should use `.with_streaming_response` when making
493
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
494
+ """
495
+ with open(file, mode="wb") as f:
496
+ for data in self.iter_bytes():
497
+ f.write(data)
498
+
499
+
500
+ class AsyncBinaryAPIResponse(AsyncAPIResponse[bytes]):
501
+ """Subclass of APIResponse providing helpers for dealing with binary data.
502
+
503
+ Note: If you want to stream the response data instead of eagerly reading it
504
+ all at once then you should use `.with_streaming_response` when making
505
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
506
+ """
507
+
508
+ async def write_to_file(
509
+ self,
510
+ file: str | os.PathLike[str],
511
+ ) -> None:
512
+ """Write the output to the given file.
513
+
514
+ Accepts a filename or any path-like object, e.g. pathlib.Path
515
+
516
+ Note: if you want to stream the data to the file instead of writing
517
+ all at once then you should use `.with_streaming_response` when making
518
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
519
+ """
520
+ path = anyio.Path(file)
521
+ async with await path.open(mode="wb") as f:
522
+ async for data in self.iter_bytes():
523
+ await f.write(data)
524
+
525
+
526
+ class StreamedBinaryAPIResponse(APIResponse[bytes]):
527
+ def stream_to_file(
528
+ self,
529
+ file: str | os.PathLike[str],
530
+ *,
531
+ chunk_size: int | None = None,
532
+ ) -> None:
533
+ """Streams the output to the given file.
534
+
535
+ Accepts a filename or any path-like object, e.g. pathlib.Path
536
+ """
537
+ with open(file, mode="wb") as f:
538
+ for data in self.iter_bytes(chunk_size):
539
+ f.write(data)
540
+
541
+
542
+ class AsyncStreamedBinaryAPIResponse(AsyncAPIResponse[bytes]):
543
+ async def stream_to_file(
544
+ self,
545
+ file: str | os.PathLike[str],
546
+ *,
547
+ chunk_size: int | None = None,
548
+ ) -> None:
549
+ """Streams the output to the given file.
550
+
551
+ Accepts a filename or any path-like object, e.g. pathlib.Path
552
+ """
553
+ path = anyio.Path(file)
554
+ async with await path.open(mode="wb") as f:
555
+ async for data in self.iter_bytes(chunk_size):
556
+ await f.write(data)
557
+
558
+
559
+ class MissingStreamClassError(TypeError):
560
+ def __init__(self) -> None:
561
+ super().__init__(
562
+ "The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `linq._streaming` for reference",
563
+ )
564
+
565
+
566
+ class StreamAlreadyConsumed(LinqApiv3Error):
567
+ """
568
+ Attempted to read or stream content, but the content has already
569
+ been streamed.
570
+
571
+ This can happen if you use a method like `.iter_lines()` and then attempt
572
+ to read th entire response body afterwards, e.g.
573
+
574
+ ```py
575
+ response = await client.post(...)
576
+ async for line in response.iter_lines():
577
+ ... # do something with `line`
578
+
579
+ content = await response.read()
580
+ # ^ error
581
+ ```
582
+
583
+ If you want this behaviour you'll need to either manually accumulate the response
584
+ content or call `await response.read()` before iterating over the stream.
585
+ """
586
+
587
+ def __init__(self) -> None:
588
+ message = (
589
+ "Attempted to read or stream some content, but the content has "
590
+ "already been streamed. "
591
+ "This could be due to attempting to stream the response "
592
+ "content more than once."
593
+ "\n\n"
594
+ "You can fix this by manually accumulating the response content while streaming "
595
+ "or by calling `.read()` before starting to stream."
596
+ )
597
+ super().__init__(message)
598
+
599
+
600
+ class ResponseContextManager(Generic[_APIResponseT]):
601
+ """Context manager for ensuring that a request is not made
602
+ until it is entered and that the response will always be closed
603
+ when the context manager exits
604
+ """
605
+
606
+ def __init__(self, request_func: Callable[[], _APIResponseT]) -> None:
607
+ self._request_func = request_func
608
+ self.__response: _APIResponseT | None = None
609
+
610
+ def __enter__(self) -> _APIResponseT:
611
+ self.__response = self._request_func()
612
+ return self.__response
613
+
614
+ def __exit__(
615
+ self,
616
+ exc_type: type[BaseException] | None,
617
+ exc: BaseException | None,
618
+ exc_tb: TracebackType | None,
619
+ ) -> None:
620
+ if self.__response is not None:
621
+ self.__response.close()
622
+
623
+
624
+ class AsyncResponseContextManager(Generic[_AsyncAPIResponseT]):
625
+ """Context manager for ensuring that a request is not made
626
+ until it is entered and that the response will always be closed
627
+ when the context manager exits
628
+ """
629
+
630
+ def __init__(self, api_request: Awaitable[_AsyncAPIResponseT]) -> None:
631
+ self._api_request = api_request
632
+ self.__response: _AsyncAPIResponseT | None = None
633
+
634
+ async def __aenter__(self) -> _AsyncAPIResponseT:
635
+ self.__response = await self._api_request
636
+ return self.__response
637
+
638
+ async def __aexit__(
639
+ self,
640
+ exc_type: type[BaseException] | None,
641
+ exc: BaseException | None,
642
+ exc_tb: TracebackType | None,
643
+ ) -> None:
644
+ if self.__response is not None:
645
+ await self.__response.close()
646
+
647
+
648
+ def to_streamed_response_wrapper(func: Callable[P, R]) -> Callable[P, ResponseContextManager[APIResponse[R]]]:
649
+ """Higher order function that takes one of our bound API methods and wraps it
650
+ to support streaming and returning the raw `APIResponse` object directly.
651
+ """
652
+
653
+ @functools.wraps(func)
654
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[APIResponse[R]]:
655
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
656
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
657
+
658
+ kwargs["extra_headers"] = extra_headers
659
+
660
+ make_request = functools.partial(func, *args, **kwargs)
661
+
662
+ return ResponseContextManager(cast(Callable[[], APIResponse[R]], make_request))
663
+
664
+ return wrapped
665
+
666
+
667
+ def async_to_streamed_response_wrapper(
668
+ func: Callable[P, Awaitable[R]],
669
+ ) -> Callable[P, AsyncResponseContextManager[AsyncAPIResponse[R]]]:
670
+ """Higher order function that takes one of our bound API methods and wraps it
671
+ to support streaming and returning the raw `APIResponse` object directly.
672
+ """
673
+
674
+ @functools.wraps(func)
675
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[AsyncAPIResponse[R]]:
676
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
677
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
678
+
679
+ kwargs["extra_headers"] = extra_headers
680
+
681
+ make_request = func(*args, **kwargs)
682
+
683
+ return AsyncResponseContextManager(cast(Awaitable[AsyncAPIResponse[R]], make_request))
684
+
685
+ return wrapped
686
+
687
+
688
+ def to_custom_streamed_response_wrapper(
689
+ func: Callable[P, object],
690
+ response_cls: type[_APIResponseT],
691
+ ) -> Callable[P, ResponseContextManager[_APIResponseT]]:
692
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
693
+ and wraps the method to support streaming and returning the given response class directly.
694
+
695
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
696
+ """
697
+
698
+ @functools.wraps(func)
699
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[_APIResponseT]:
700
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
701
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
702
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
703
+
704
+ kwargs["extra_headers"] = extra_headers
705
+
706
+ make_request = functools.partial(func, *args, **kwargs)
707
+
708
+ return ResponseContextManager(cast(Callable[[], _APIResponseT], make_request))
709
+
710
+ return wrapped
711
+
712
+
713
+ def async_to_custom_streamed_response_wrapper(
714
+ func: Callable[P, Awaitable[object]],
715
+ response_cls: type[_AsyncAPIResponseT],
716
+ ) -> Callable[P, AsyncResponseContextManager[_AsyncAPIResponseT]]:
717
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
718
+ and wraps the method to support streaming and returning the given response class directly.
719
+
720
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
721
+ """
722
+
723
+ @functools.wraps(func)
724
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[_AsyncAPIResponseT]:
725
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
726
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
727
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
728
+
729
+ kwargs["extra_headers"] = extra_headers
730
+
731
+ make_request = func(*args, **kwargs)
732
+
733
+ return AsyncResponseContextManager(cast(Awaitable[_AsyncAPIResponseT], make_request))
734
+
735
+ return wrapped
736
+
737
+
738
+ def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, APIResponse[R]]:
739
+ """Higher order function that takes one of our bound API methods and wraps it
740
+ to support returning the raw `APIResponse` object directly.
741
+ """
742
+
743
+ @functools.wraps(func)
744
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> APIResponse[R]:
745
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
746
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
747
+
748
+ kwargs["extra_headers"] = extra_headers
749
+
750
+ return cast(APIResponse[R], func(*args, **kwargs))
751
+
752
+ return wrapped
753
+
754
+
755
+ def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[AsyncAPIResponse[R]]]:
756
+ """Higher order function that takes one of our bound API methods and wraps it
757
+ to support returning the raw `APIResponse` object directly.
758
+ """
759
+
760
+ @functools.wraps(func)
761
+ async def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncAPIResponse[R]:
762
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
763
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
764
+
765
+ kwargs["extra_headers"] = extra_headers
766
+
767
+ return cast(AsyncAPIResponse[R], await func(*args, **kwargs))
768
+
769
+ return wrapped
770
+
771
+
772
+ def to_custom_raw_response_wrapper(
773
+ func: Callable[P, object],
774
+ response_cls: type[_APIResponseT],
775
+ ) -> Callable[P, _APIResponseT]:
776
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
777
+ and wraps the method to support returning the given response class directly.
778
+
779
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
780
+ """
781
+
782
+ @functools.wraps(func)
783
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> _APIResponseT:
784
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
785
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
786
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
787
+
788
+ kwargs["extra_headers"] = extra_headers
789
+
790
+ return cast(_APIResponseT, func(*args, **kwargs))
791
+
792
+ return wrapped
793
+
794
+
795
+ def async_to_custom_raw_response_wrapper(
796
+ func: Callable[P, Awaitable[object]],
797
+ response_cls: type[_AsyncAPIResponseT],
798
+ ) -> Callable[P, Awaitable[_AsyncAPIResponseT]]:
799
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
800
+ and wraps the method to support returning the given response class directly.
801
+
802
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
803
+ """
804
+
805
+ @functools.wraps(func)
806
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> Awaitable[_AsyncAPIResponseT]:
807
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
808
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
809
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
810
+
811
+ kwargs["extra_headers"] = extra_headers
812
+
813
+ return cast(Awaitable[_AsyncAPIResponseT], func(*args, **kwargs))
814
+
815
+ return wrapped
816
+
817
+
818
+ def extract_response_type(typ: type[BaseAPIResponse[Any]]) -> type:
819
+ """Given a type like `APIResponse[T]`, returns the generic type variable `T`.
820
+
821
+ This also handles the case where a concrete subclass is given, e.g.
822
+ ```py
823
+ class MyResponse(APIResponse[bytes]):
824
+ ...
825
+
826
+ extract_response_type(MyResponse) -> bytes
827
+ ```
828
+ """
829
+ return extract_type_var_from_base(
830
+ typ,
831
+ generic_bases=cast("tuple[type, ...]", (BaseAPIResponse, APIResponse, AsyncAPIResponse)),
832
+ index=0,
833
+ )