chunkify-analytics-sdk 0.9.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 (179) hide show
  1. chunkify_analytics/__init__.py +102 -0
  2. chunkify_analytics/_base_client.py +2153 -0
  3. chunkify_analytics/_client.py +1262 -0
  4. chunkify_analytics/_compat.py +226 -0
  5. chunkify_analytics/_constants.py +14 -0
  6. chunkify_analytics/_exceptions.py +108 -0
  7. chunkify_analytics/_files.py +173 -0
  8. chunkify_analytics/_models.py +964 -0
  9. chunkify_analytics/_qs.py +149 -0
  10. chunkify_analytics/_resource.py +43 -0
  11. chunkify_analytics/_response.py +835 -0
  12. chunkify_analytics/_streaming.py +338 -0
  13. chunkify_analytics/_types.py +274 -0
  14. chunkify_analytics/_utils/__init__.py +64 -0
  15. chunkify_analytics/_utils/_compat.py +45 -0
  16. chunkify_analytics/_utils/_datetime_parse.py +136 -0
  17. chunkify_analytics/_utils/_json.py +35 -0
  18. chunkify_analytics/_utils/_logs.py +25 -0
  19. chunkify_analytics/_utils/_path.py +127 -0
  20. chunkify_analytics/_utils/_proxy.py +65 -0
  21. chunkify_analytics/_utils/_reflection.py +42 -0
  22. chunkify_analytics/_utils/_resources_proxy.py +24 -0
  23. chunkify_analytics/_utils/_streams.py +12 -0
  24. chunkify_analytics/_utils/_sync.py +58 -0
  25. chunkify_analytics/_utils/_transform.py +457 -0
  26. chunkify_analytics/_utils/_typing.py +156 -0
  27. chunkify_analytics/_utils/_utils.py +433 -0
  28. chunkify_analytics/_version.py +4 -0
  29. chunkify_analytics/lib/.keep +4 -0
  30. chunkify_analytics/pagination.py +221 -0
  31. chunkify_analytics/py.typed +0 -0
  32. chunkify_analytics/resources/__init__.py +243 -0
  33. chunkify_analytics/resources/admin/__init__.py +33 -0
  34. chunkify_analytics/resources/admin/admin.py +253 -0
  35. chunkify_analytics/resources/admin/keys.py +283 -0
  36. chunkify_analytics/resources/dimensions.py +436 -0
  37. chunkify_analytics/resources/engagement.py +479 -0
  38. chunkify_analytics/resources/errors.py +400 -0
  39. chunkify_analytics/resources/events.py +562 -0
  40. chunkify_analytics/resources/exports.py +584 -0
  41. chunkify_analytics/resources/health.py +159 -0
  42. chunkify_analytics/resources/playback_rates.py +391 -0
  43. chunkify_analytics/resources/project/__init__.py +33 -0
  44. chunkify_analytics/resources/project/keys.py +379 -0
  45. chunkify_analytics/resources/project/project.py +322 -0
  46. chunkify_analytics/resources/quality.py +471 -0
  47. chunkify_analytics/resources/renditions.py +391 -0
  48. chunkify_analytics/resources/retention.py +377 -0
  49. chunkify_analytics/resources/subtitles.py +389 -0
  50. chunkify_analytics/resources/summary.py +469 -0
  51. chunkify_analytics/resources/timeseries.py +399 -0
  52. chunkify_analytics/resources/videos.py +424 -0
  53. chunkify_analytics/resources/views.py +579 -0
  54. chunkify_analytics/types/__init__.py +145 -0
  55. chunkify_analytics/types/admin/__init__.py +3 -0
  56. chunkify_analytics/types/admin_create_project_params.py +25 -0
  57. chunkify_analytics/types/analytics_event.py +32 -0
  58. chunkify_analytics/types/analytics_event_param.py +30 -0
  59. chunkify_analytics/types/created_project.py +37 -0
  60. chunkify_analytics/types/created_project_key.py +34 -0
  61. chunkify_analytics/types/deleted_project.py +18 -0
  62. chunkify_analytics/types/dimension_list_values_params.py +124 -0
  63. chunkify_analytics/types/dimension_values.py +42 -0
  64. chunkify_analytics/types/engagement.py +60 -0
  65. chunkify_analytics/types/engagement_breakdown_page.py +44 -0
  66. chunkify_analytics/types/engagement_response.py +11 -0
  67. chunkify_analytics/types/engagement_retrieve_params.py +158 -0
  68. chunkify_analytics/types/engagement_timeseries.py +28 -0
  69. chunkify_analytics/types/engagement_timeseries_bucket.py +63 -0
  70. chunkify_analytics/types/error_group.py +17 -0
  71. chunkify_analytics/types/error_list_params.py +124 -0
  72. chunkify_analytics/types/error_page.py +14 -0
  73. chunkify_analytics/types/event_ingest_params.py +19 -0
  74. chunkify_analytics/types/event_ingest_response.py +11 -0
  75. chunkify_analytics/types/event_list_params.py +146 -0
  76. chunkify_analytics/types/event_page.py +18 -0
  77. chunkify_analytics/types/export.py +18 -0
  78. chunkify_analytics/types/export_columns.py +12 -0
  79. chunkify_analytics/types/export_create_params.py +40 -0
  80. chunkify_analytics/types/export_download_response.py +7 -0
  81. chunkify_analytics/types/export_list_columns_params.py +69 -0
  82. chunkify_analytics/types/export_query_param.py +141 -0
  83. chunkify_analytics/types/health.py +11 -0
  84. chunkify_analytics/types/metrics.py +13 -0
  85. chunkify_analytics/types/metrics_breakdown_page.py +40 -0
  86. chunkify_analytics/types/metrics_response.py +11 -0
  87. chunkify_analytics/types/native_created.py +13 -0
  88. chunkify_analytics/types/native_duplicate.py +13 -0
  89. chunkify_analytics/types/playback_error.py +180 -0
  90. chunkify_analytics/types/playback_error_param.py +182 -0
  91. chunkify_analytics/types/playback_rate_changed.py +150 -0
  92. chunkify_analytics/types/playback_rate_changed_param.py +152 -0
  93. chunkify_analytics/types/playback_rate_metric.py +21 -0
  94. chunkify_analytics/types/playback_rate_report.py +31 -0
  95. chunkify_analytics/types/playback_rate_retrieve_params.py +117 -0
  96. chunkify_analytics/types/playback_state_changed.py +150 -0
  97. chunkify_analytics/types/playback_state_changed_param.py +156 -0
  98. chunkify_analytics/types/project/__init__.py +6 -0
  99. chunkify_analytics/types/project/key_create_params.py +21 -0
  100. chunkify_analytics/types/project/project.py +35 -0
  101. chunkify_analytics/types/project_key.py +21 -0
  102. chunkify_analytics/types/project_keys.py +14 -0
  103. chunkify_analytics/types/project_update_params.py +25 -0
  104. chunkify_analytics/types/quality.py +117 -0
  105. chunkify_analytics/types/quality_breakdown_page.py +44 -0
  106. chunkify_analytics/types/quality_response.py +11 -0
  107. chunkify_analytics/types/quality_retrieve_params.py +158 -0
  108. chunkify_analytics/types/quality_timeseries.py +28 -0
  109. chunkify_analytics/types/quality_timeseries_bucket.py +120 -0
  110. chunkify_analytics/types/rendition_changed.py +156 -0
  111. chunkify_analytics/types/rendition_changed_param.py +158 -0
  112. chunkify_analytics/types/rendition_metric.py +40 -0
  113. chunkify_analytics/types/rendition_report.py +43 -0
  114. chunkify_analytics/types/rendition_retrieve_params.py +117 -0
  115. chunkify_analytics/types/retention_bucket.py +22 -0
  116. chunkify_analytics/types/retention_report.py +33 -0
  117. chunkify_analytics/types/retention_retrieve_params.py +110 -0
  118. chunkify_analytics/types/rotated_project_key.py +29 -0
  119. chunkify_analytics/types/seek_completed.py +166 -0
  120. chunkify_analytics/types/seek_completed_param.py +168 -0
  121. chunkify_analytics/types/shared/__init__.py +24 -0
  122. chunkify_analytics/types/shared/browser_context.py +62 -0
  123. chunkify_analytics/types/shared/custom_dimensions.py +8 -0
  124. chunkify_analytics/types/shared/event_context.py +161 -0
  125. chunkify_analytics/types/shared/event_envelope.py +152 -0
  126. chunkify_analytics/types/shared/metric_count_ratio.py +18 -0
  127. chunkify_analytics/types/shared/otlp_any_value.py +56 -0
  128. chunkify_analytics/types/shared/otlp_attribute.py +24 -0
  129. chunkify_analytics/types/shared/otlp_attribute_value.py +136 -0
  130. chunkify_analytics/types/shared/otlp_context_attribute.py +22 -0
  131. chunkify_analytics/types/shared/otlp_log_record.py +48 -0
  132. chunkify_analytics/types/shared/otlp_resource.py +20 -0
  133. chunkify_analytics/types/shared/otlp_scope.py +24 -0
  134. chunkify_analytics/types/shared/playback_rate_playing_time.py +12 -0
  135. chunkify_analytics/types/shared/playback_score.py +28 -0
  136. chunkify_analytics/types/shared/played_range.py +13 -0
  137. chunkify_analytics/types/shared/progress_reached.py +39 -0
  138. chunkify_analytics/types/shared/rendition_playing_time.py +21 -0
  139. chunkify_analytics/types/shared/startup_outcomes.py +39 -0
  140. chunkify_analytics/types/shared/stored_otlp_context.py +50 -0
  141. chunkify_analytics/types/shared/subtitle_playing_time.py +14 -0
  142. chunkify_analytics/types/shared/view_metrics.py +100 -0
  143. chunkify_analytics/types/shared/watch_time_distribution.py +41 -0
  144. chunkify_analytics/types/shared_params/__init__.py +8 -0
  145. chunkify_analytics/types/shared_params/browser_context.py +62 -0
  146. chunkify_analytics/types/shared_params/custom_dimensions.py +10 -0
  147. chunkify_analytics/types/shared_params/playback_rate_playing_time.py +14 -0
  148. chunkify_analytics/types/shared_params/played_range.py +15 -0
  149. chunkify_analytics/types/shared_params/rendition_playing_time.py +22 -0
  150. chunkify_analytics/types/shared_params/subtitle_playing_time.py +15 -0
  151. chunkify_analytics/types/stored_event.py +44 -0
  152. chunkify_analytics/types/subtitle_changed.py +150 -0
  153. chunkify_analytics/types/subtitle_changed_param.py +152 -0
  154. chunkify_analytics/types/subtitle_metric.py +26 -0
  155. chunkify_analytics/types/subtitle_report.py +31 -0
  156. chunkify_analytics/types/subtitle_retrieve_params.py +117 -0
  157. chunkify_analytics/types/summary_retrieve_params.py +158 -0
  158. chunkify_analytics/types/time_bucket.py +22 -0
  159. chunkify_analytics/types/timeseries.py +28 -0
  160. chunkify_analytics/types/timeseries_response.py +12 -0
  161. chunkify_analytics/types/timesery_retrieve_params.py +115 -0
  162. chunkify_analytics/types/video_list_params.py +140 -0
  163. chunkify_analytics/types/video_metrics.py +23 -0
  164. chunkify_analytics/types/video_page.py +14 -0
  165. chunkify_analytics/types/view.py +43 -0
  166. chunkify_analytics/types/view_detail.py +21 -0
  167. chunkify_analytics/types/view_ended.py +180 -0
  168. chunkify_analytics/types/view_ended_param.py +182 -0
  169. chunkify_analytics/types/view_list_params.py +152 -0
  170. chunkify_analytics/types/view_page.py +14 -0
  171. chunkify_analytics/types/view_retrieve_params.py +23 -0
  172. chunkify_analytics/types/view_snapshot.py +180 -0
  173. chunkify_analytics/types/view_snapshot_param.py +182 -0
  174. chunkify_analytics/types/view_started.py +192 -0
  175. chunkify_analytics/types/view_started_param.py +194 -0
  176. chunkify_analytics_sdk-0.9.0.dist-info/METADATA +487 -0
  177. chunkify_analytics_sdk-0.9.0.dist-info/RECORD +179 -0
  178. chunkify_analytics_sdk-0.9.0.dist-info/WHEEL +4 -0
  179. chunkify_analytics_sdk-0.9.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,835 @@
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 ChunkifyAnalyticsError, 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(
224
+ "Pydantic models must subclass our base model type, e.g. `from chunkify_analytics import BaseModel`"
225
+ )
226
+
227
+ if (
228
+ cast_to is not object
229
+ and not origin is list
230
+ and not origin is dict
231
+ and not origin is Union
232
+ and not issubclass(origin, BaseModel)
233
+ ):
234
+ raise RuntimeError(
235
+ f"Unsupported type, expected {cast_to} to be a subclass of {BaseModel}, {dict}, {list}, {Union}, {NoneType}, {str} or {httpx.Response}."
236
+ )
237
+
238
+ # split is required to handle cases where additional information is included
239
+ # in the response, e.g. application/json; charset=utf-8
240
+ content_type, *_ = response.headers.get("content-type", "*").split(";")
241
+ if not content_type.endswith("json"):
242
+ if is_basemodel(cast_to):
243
+ try:
244
+ data = response.json()
245
+ except Exception as exc:
246
+ log.debug("Could not read JSON from response data due to %s - %s", type(exc), exc)
247
+ else:
248
+ return self._client._process_response_data(
249
+ data=data,
250
+ cast_to=cast_to, # type: ignore
251
+ response=response,
252
+ )
253
+
254
+ if self._client._strict_response_validation:
255
+ raise APIResponseValidationError(
256
+ response=response,
257
+ message=f"Expected Content-Type response header to be `application/json` but received `{content_type}` instead.",
258
+ body=response.text,
259
+ )
260
+
261
+ # If the API responds with content that isn't JSON then we just return
262
+ # the (decoded) text without performing any parsing so that you can still
263
+ # handle the response however you need to.
264
+ return response.text # type: ignore
265
+
266
+ data = response.json()
267
+
268
+ return self._client._process_response_data(
269
+ data=data,
270
+ cast_to=cast_to, # type: ignore
271
+ response=response,
272
+ )
273
+
274
+
275
+ class APIResponse(BaseAPIResponse[R]):
276
+ @overload
277
+ def parse(self, *, to: type[_T]) -> _T: ...
278
+
279
+ @overload
280
+ def parse(self) -> R: ...
281
+
282
+ def parse(self, *, to: type[_T] | None = None) -> R | _T:
283
+ """Returns the rich python representation of this response's data.
284
+
285
+ For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
286
+
287
+ You can customise the type that the response is parsed into through
288
+ the `to` argument, e.g.
289
+
290
+ ```py
291
+ from chunkify_analytics import BaseModel
292
+
293
+
294
+ class MyModel(BaseModel):
295
+ foo: str
296
+
297
+
298
+ obj = response.parse(to=MyModel)
299
+ print(obj.foo)
300
+ ```
301
+
302
+ We support parsing:
303
+ - `BaseModel`
304
+ - `dict`
305
+ - `list`
306
+ - `Union`
307
+ - `str`
308
+ - `int`
309
+ - `float`
310
+ - `httpx.Response`
311
+ """
312
+ cache_key = to if to is not None else self._cast_to
313
+ cached = self._parsed_by_type.get(cache_key)
314
+ if cached is not None:
315
+ return cached # type: ignore[no-any-return]
316
+
317
+ if not self._is_sse_stream:
318
+ self.read()
319
+
320
+ parsed = self._parse(to=to)
321
+ if is_given(self._options.post_parser):
322
+ parsed = self._options.post_parser(parsed)
323
+
324
+ self._parsed_by_type[cache_key] = parsed
325
+ return parsed
326
+
327
+ def read(self) -> bytes:
328
+ """Read and return the binary response content."""
329
+ try:
330
+ return self.http_response.read()
331
+ except httpx.StreamConsumed as exc:
332
+ # The default error raised by httpx isn't very
333
+ # helpful in our case so we re-raise it with
334
+ # a different error message.
335
+ raise StreamAlreadyConsumed() from exc
336
+
337
+ def text(self) -> str:
338
+ """Read and decode the response content into a string."""
339
+ self.read()
340
+ return self.http_response.text
341
+
342
+ def json(self) -> object:
343
+ """Read and decode the JSON response content."""
344
+ self.read()
345
+ return self.http_response.json()
346
+
347
+ def close(self) -> None:
348
+ """Close the response and release the connection.
349
+
350
+ Automatically called if the response body is read to completion.
351
+ """
352
+ self.http_response.close()
353
+
354
+ def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
355
+ """
356
+ A byte-iterator over the decoded response content.
357
+
358
+ This automatically handles gzip, deflate and brotli encoded responses.
359
+ """
360
+ for chunk in self.http_response.iter_bytes(chunk_size):
361
+ yield chunk
362
+
363
+ def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
364
+ """A str-iterator over the decoded response content
365
+ that handles both gzip, deflate, etc but also detects the content's
366
+ string encoding.
367
+ """
368
+ for chunk in self.http_response.iter_text(chunk_size):
369
+ yield chunk
370
+
371
+ def iter_lines(self) -> Iterator[str]:
372
+ """Like `iter_text()` but will only yield chunks for each line"""
373
+ for chunk in self.http_response.iter_lines():
374
+ yield chunk
375
+
376
+
377
+ class AsyncAPIResponse(BaseAPIResponse[R]):
378
+ @overload
379
+ async def parse(self, *, to: type[_T]) -> _T: ...
380
+
381
+ @overload
382
+ async def parse(self) -> R: ...
383
+
384
+ async def parse(self, *, to: type[_T] | None = None) -> R | _T:
385
+ """Returns the rich python representation of this response's data.
386
+
387
+ For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
388
+
389
+ You can customise the type that the response is parsed into through
390
+ the `to` argument, e.g.
391
+
392
+ ```py
393
+ from chunkify_analytics import BaseModel
394
+
395
+
396
+ class MyModel(BaseModel):
397
+ foo: str
398
+
399
+
400
+ obj = response.parse(to=MyModel)
401
+ print(obj.foo)
402
+ ```
403
+
404
+ We support parsing:
405
+ - `BaseModel`
406
+ - `dict`
407
+ - `list`
408
+ - `Union`
409
+ - `str`
410
+ - `httpx.Response`
411
+ """
412
+ cache_key = to if to is not None else self._cast_to
413
+ cached = self._parsed_by_type.get(cache_key)
414
+ if cached is not None:
415
+ return cached # type: ignore[no-any-return]
416
+
417
+ if not self._is_sse_stream:
418
+ await self.read()
419
+
420
+ parsed = self._parse(to=to)
421
+ if is_given(self._options.post_parser):
422
+ parsed = self._options.post_parser(parsed)
423
+
424
+ self._parsed_by_type[cache_key] = parsed
425
+ return parsed
426
+
427
+ async def read(self) -> bytes:
428
+ """Read and return the binary response content."""
429
+ try:
430
+ return await self.http_response.aread()
431
+ except httpx.StreamConsumed as exc:
432
+ # the default error raised by httpx isn't very
433
+ # helpful in our case so we re-raise it with
434
+ # a different error message
435
+ raise StreamAlreadyConsumed() from exc
436
+
437
+ async def text(self) -> str:
438
+ """Read and decode the response content into a string."""
439
+ await self.read()
440
+ return self.http_response.text
441
+
442
+ async def json(self) -> object:
443
+ """Read and decode the JSON response content."""
444
+ await self.read()
445
+ return self.http_response.json()
446
+
447
+ async def close(self) -> None:
448
+ """Close the response and release the connection.
449
+
450
+ Automatically called if the response body is read to completion.
451
+ """
452
+ await self.http_response.aclose()
453
+
454
+ async def iter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
455
+ """
456
+ A byte-iterator over the decoded response content.
457
+
458
+ This automatically handles gzip, deflate and brotli encoded responses.
459
+ """
460
+ async for chunk in self.http_response.aiter_bytes(chunk_size):
461
+ yield chunk
462
+
463
+ async def iter_text(self, chunk_size: int | None = None) -> AsyncIterator[str]:
464
+ """A str-iterator over the decoded response content
465
+ that handles both gzip, deflate, etc but also detects the content's
466
+ string encoding.
467
+ """
468
+ async for chunk in self.http_response.aiter_text(chunk_size):
469
+ yield chunk
470
+
471
+ async def iter_lines(self) -> AsyncIterator[str]:
472
+ """Like `iter_text()` but will only yield chunks for each line"""
473
+ async for chunk in self.http_response.aiter_lines():
474
+ yield chunk
475
+
476
+
477
+ class BinaryAPIResponse(APIResponse[bytes]):
478
+ """Subclass of APIResponse providing helpers for dealing with binary data.
479
+
480
+ Note: If you want to stream the response data instead of eagerly reading it
481
+ all at once then you should use `.with_streaming_response` when making
482
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
483
+ """
484
+
485
+ def write_to_file(
486
+ self,
487
+ file: str | os.PathLike[str],
488
+ ) -> None:
489
+ """Write the output to the given file.
490
+
491
+ Accepts a filename or any path-like object, e.g. pathlib.Path
492
+
493
+ Note: if you want to stream the data to the file instead of writing
494
+ all at once then you should use `.with_streaming_response` when making
495
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
496
+ """
497
+ with open(file, mode="wb") as f:
498
+ for data in self.iter_bytes():
499
+ f.write(data)
500
+
501
+
502
+ class AsyncBinaryAPIResponse(AsyncAPIResponse[bytes]):
503
+ """Subclass of APIResponse providing helpers for dealing with binary data.
504
+
505
+ Note: If you want to stream the response data instead of eagerly reading it
506
+ all at once then you should use `.with_streaming_response` when making
507
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
508
+ """
509
+
510
+ async def write_to_file(
511
+ self,
512
+ file: str | os.PathLike[str],
513
+ ) -> None:
514
+ """Write the output to the given file.
515
+
516
+ Accepts a filename or any path-like object, e.g. pathlib.Path
517
+
518
+ Note: if you want to stream the data to the file instead of writing
519
+ all at once then you should use `.with_streaming_response` when making
520
+ the API request, e.g. `.with_streaming_response.get_binary_response()`
521
+ """
522
+ path = anyio.Path(file)
523
+ async with await path.open(mode="wb") as f:
524
+ async for data in self.iter_bytes():
525
+ await f.write(data)
526
+
527
+
528
+ class StreamedBinaryAPIResponse(APIResponse[bytes]):
529
+ def stream_to_file(
530
+ self,
531
+ file: str | os.PathLike[str],
532
+ *,
533
+ chunk_size: int | None = None,
534
+ ) -> None:
535
+ """Streams the output to the given file.
536
+
537
+ Accepts a filename or any path-like object, e.g. pathlib.Path
538
+ """
539
+ with open(file, mode="wb") as f:
540
+ for data in self.iter_bytes(chunk_size):
541
+ f.write(data)
542
+
543
+
544
+ class AsyncStreamedBinaryAPIResponse(AsyncAPIResponse[bytes]):
545
+ async def stream_to_file(
546
+ self,
547
+ file: str | os.PathLike[str],
548
+ *,
549
+ chunk_size: int | None = None,
550
+ ) -> None:
551
+ """Streams the output to the given file.
552
+
553
+ Accepts a filename or any path-like object, e.g. pathlib.Path
554
+ """
555
+ path = anyio.Path(file)
556
+ async with await path.open(mode="wb") as f:
557
+ async for data in self.iter_bytes(chunk_size):
558
+ await f.write(data)
559
+
560
+
561
+ class MissingStreamClassError(TypeError):
562
+ def __init__(self) -> None:
563
+ super().__init__(
564
+ "The `stream` argument was set to `True` but the `stream_cls` argument was not given. See `chunkify_analytics._streaming` for reference",
565
+ )
566
+
567
+
568
+ class StreamAlreadyConsumed(ChunkifyAnalyticsError):
569
+ """
570
+ Attempted to read or stream content, but the content has already
571
+ been streamed.
572
+
573
+ This can happen if you use a method like `.iter_lines()` and then attempt
574
+ to read th entire response body afterwards, e.g.
575
+
576
+ ```py
577
+ response = await client.post(...)
578
+ async for line in response.iter_lines():
579
+ ... # do something with `line`
580
+
581
+ content = await response.read()
582
+ # ^ error
583
+ ```
584
+
585
+ If you want this behaviour you'll need to either manually accumulate the response
586
+ content or call `await response.read()` before iterating over the stream.
587
+ """
588
+
589
+ def __init__(self) -> None:
590
+ message = (
591
+ "Attempted to read or stream some content, but the content has "
592
+ "already been streamed. "
593
+ "This could be due to attempting to stream the response "
594
+ "content more than once."
595
+ "\n\n"
596
+ "You can fix this by manually accumulating the response content while streaming "
597
+ "or by calling `.read()` before starting to stream."
598
+ )
599
+ super().__init__(message)
600
+
601
+
602
+ class ResponseContextManager(Generic[_APIResponseT]):
603
+ """Context manager for ensuring that a request is not made
604
+ until it is entered and that the response will always be closed
605
+ when the context manager exits
606
+ """
607
+
608
+ def __init__(self, request_func: Callable[[], _APIResponseT]) -> None:
609
+ self._request_func = request_func
610
+ self.__response: _APIResponseT | None = None
611
+
612
+ def __enter__(self) -> _APIResponseT:
613
+ self.__response = self._request_func()
614
+ return self.__response
615
+
616
+ def __exit__(
617
+ self,
618
+ exc_type: type[BaseException] | None,
619
+ exc: BaseException | None,
620
+ exc_tb: TracebackType | None,
621
+ ) -> None:
622
+ if self.__response is not None:
623
+ self.__response.close()
624
+
625
+
626
+ class AsyncResponseContextManager(Generic[_AsyncAPIResponseT]):
627
+ """Context manager for ensuring that a request is not made
628
+ until it is entered and that the response will always be closed
629
+ when the context manager exits
630
+ """
631
+
632
+ def __init__(self, api_request: Awaitable[_AsyncAPIResponseT]) -> None:
633
+ self._api_request = api_request
634
+ self.__response: _AsyncAPIResponseT | None = None
635
+
636
+ async def __aenter__(self) -> _AsyncAPIResponseT:
637
+ self.__response = await self._api_request
638
+ return self.__response
639
+
640
+ async def __aexit__(
641
+ self,
642
+ exc_type: type[BaseException] | None,
643
+ exc: BaseException | None,
644
+ exc_tb: TracebackType | None,
645
+ ) -> None:
646
+ if self.__response is not None:
647
+ await self.__response.close()
648
+
649
+
650
+ def to_streamed_response_wrapper(func: Callable[P, R]) -> Callable[P, ResponseContextManager[APIResponse[R]]]:
651
+ """Higher order function that takes one of our bound API methods and wraps it
652
+ to support streaming and returning the raw `APIResponse` object directly.
653
+ """
654
+
655
+ @functools.wraps(func)
656
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[APIResponse[R]]:
657
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
658
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
659
+
660
+ kwargs["extra_headers"] = extra_headers
661
+
662
+ make_request = functools.partial(func, *args, **kwargs)
663
+
664
+ return ResponseContextManager(cast(Callable[[], APIResponse[R]], make_request))
665
+
666
+ return wrapped
667
+
668
+
669
+ def async_to_streamed_response_wrapper(
670
+ func: Callable[P, Awaitable[R]],
671
+ ) -> Callable[P, AsyncResponseContextManager[AsyncAPIResponse[R]]]:
672
+ """Higher order function that takes one of our bound API methods and wraps it
673
+ to support streaming and returning the raw `APIResponse` object directly.
674
+ """
675
+
676
+ @functools.wraps(func)
677
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[AsyncAPIResponse[R]]:
678
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
679
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
680
+
681
+ kwargs["extra_headers"] = extra_headers
682
+
683
+ make_request = func(*args, **kwargs)
684
+
685
+ return AsyncResponseContextManager(cast(Awaitable[AsyncAPIResponse[R]], make_request))
686
+
687
+ return wrapped
688
+
689
+
690
+ def to_custom_streamed_response_wrapper(
691
+ func: Callable[P, object],
692
+ response_cls: type[_APIResponseT],
693
+ ) -> Callable[P, ResponseContextManager[_APIResponseT]]:
694
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
695
+ and wraps the method to support streaming and returning the given response class directly.
696
+
697
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
698
+ """
699
+
700
+ @functools.wraps(func)
701
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> ResponseContextManager[_APIResponseT]:
702
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
703
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
704
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
705
+
706
+ kwargs["extra_headers"] = extra_headers
707
+
708
+ make_request = functools.partial(func, *args, **kwargs)
709
+
710
+ return ResponseContextManager(cast(Callable[[], _APIResponseT], make_request))
711
+
712
+ return wrapped
713
+
714
+
715
+ def async_to_custom_streamed_response_wrapper(
716
+ func: Callable[P, Awaitable[object]],
717
+ response_cls: type[_AsyncAPIResponseT],
718
+ ) -> Callable[P, AsyncResponseContextManager[_AsyncAPIResponseT]]:
719
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
720
+ and wraps the method to support streaming and returning the given response class directly.
721
+
722
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
723
+ """
724
+
725
+ @functools.wraps(func)
726
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncResponseContextManager[_AsyncAPIResponseT]:
727
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
728
+ extra_headers[RAW_RESPONSE_HEADER] = "stream"
729
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
730
+
731
+ kwargs["extra_headers"] = extra_headers
732
+
733
+ make_request = func(*args, **kwargs)
734
+
735
+ return AsyncResponseContextManager(cast(Awaitable[_AsyncAPIResponseT], make_request))
736
+
737
+ return wrapped
738
+
739
+
740
+ def to_raw_response_wrapper(func: Callable[P, R]) -> Callable[P, APIResponse[R]]:
741
+ """Higher order function that takes one of our bound API methods and wraps it
742
+ to support returning the raw `APIResponse` object directly.
743
+ """
744
+
745
+ @functools.wraps(func)
746
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> APIResponse[R]:
747
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
748
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
749
+
750
+ kwargs["extra_headers"] = extra_headers
751
+
752
+ return cast(APIResponse[R], func(*args, **kwargs))
753
+
754
+ return wrapped
755
+
756
+
757
+ def async_to_raw_response_wrapper(func: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[AsyncAPIResponse[R]]]:
758
+ """Higher order function that takes one of our bound API methods and wraps it
759
+ to support returning the raw `APIResponse` object directly.
760
+ """
761
+
762
+ @functools.wraps(func)
763
+ async def wrapped(*args: P.args, **kwargs: P.kwargs) -> AsyncAPIResponse[R]:
764
+ extra_headers: dict[str, str] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
765
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
766
+
767
+ kwargs["extra_headers"] = extra_headers
768
+
769
+ return cast(AsyncAPIResponse[R], await func(*args, **kwargs))
770
+
771
+ return wrapped
772
+
773
+
774
+ def to_custom_raw_response_wrapper(
775
+ func: Callable[P, object],
776
+ response_cls: type[_APIResponseT],
777
+ ) -> Callable[P, _APIResponseT]:
778
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
779
+ and wraps the method to support returning the given response class directly.
780
+
781
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
782
+ """
783
+
784
+ @functools.wraps(func)
785
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> _APIResponseT:
786
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
787
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
788
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
789
+
790
+ kwargs["extra_headers"] = extra_headers
791
+
792
+ return cast(_APIResponseT, func(*args, **kwargs))
793
+
794
+ return wrapped
795
+
796
+
797
+ def async_to_custom_raw_response_wrapper(
798
+ func: Callable[P, Awaitable[object]],
799
+ response_cls: type[_AsyncAPIResponseT],
800
+ ) -> Callable[P, Awaitable[_AsyncAPIResponseT]]:
801
+ """Higher order function that takes one of our bound API methods and an `APIResponse` class
802
+ and wraps the method to support returning the given response class directly.
803
+
804
+ Note: the given `response_cls` *must* be concrete, e.g. `class BinaryAPIResponse(APIResponse[bytes])`
805
+ """
806
+
807
+ @functools.wraps(func)
808
+ def wrapped(*args: P.args, **kwargs: P.kwargs) -> Awaitable[_AsyncAPIResponseT]:
809
+ extra_headers: dict[str, Any] = {**(cast(Any, kwargs.get("extra_headers")) or {})}
810
+ extra_headers[RAW_RESPONSE_HEADER] = "raw"
811
+ extra_headers[OVERRIDE_CAST_TO_HEADER] = response_cls
812
+
813
+ kwargs["extra_headers"] = extra_headers
814
+
815
+ return cast(Awaitable[_AsyncAPIResponseT], func(*args, **kwargs))
816
+
817
+ return wrapped
818
+
819
+
820
+ def extract_response_type(typ: type[BaseAPIResponse[Any]]) -> type:
821
+ """Given a type like `APIResponse[T]`, returns the generic type variable `T`.
822
+
823
+ This also handles the case where a concrete subclass is given, e.g.
824
+ ```py
825
+ class MyResponse(APIResponse[bytes]):
826
+ ...
827
+
828
+ extract_response_type(MyResponse) -> bytes
829
+ ```
830
+ """
831
+ return extract_type_var_from_base(
832
+ typ,
833
+ generic_bases=cast("tuple[type, ...]", (BaseAPIResponse, APIResponse, AsyncAPIResponse)),
834
+ index=0,
835
+ )