devupai 1.0.0a1__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.
- devupai/__init__.py +85 -0
- devupai/_client.py +1154 -0
- devupai/_errors.py +314 -0
- devupai/_response.py +225 -0
- devupai/_streaming.py +515 -0
- devupai/_version.py +3 -0
- devupai/py.typed +0 -0
- devupai/resources/__init__.py +137 -0
- devupai/resources/_base.py +207 -0
- devupai/resources/audio.py +663 -0
- devupai/resources/balance.py +103 -0
- devupai/resources/chat.py +428 -0
- devupai/resources/embeddings.py +141 -0
- devupai/resources/health.py +113 -0
- devupai/resources/images.py +503 -0
- devupai/resources/inference.py +347 -0
- devupai/resources/me.py +208 -0
- devupai/resources/models.py +405 -0
- devupai/resources/rerank.py +147 -0
- devupai/resources/responses.py +400 -0
- devupai/resources/shared.py +314 -0
- devupai/resources/video.py +600 -0
- devupai/types/__init__.py +264 -0
- devupai/types/_base.py +167 -0
- devupai/types/account.py +48 -0
- devupai/types/audio.py +89 -0
- devupai/types/chat.py +284 -0
- devupai/types/embeddings.py +51 -0
- devupai/types/images.py +238 -0
- devupai/types/models.py +107 -0
- devupai/types/rerank.py +41 -0
- devupai/types/responses.py +219 -0
- devupai/types/shared.py +79 -0
- devupai/types/video.py +218 -0
- devupai/types/webhooks.py +61 -0
- devupai/webhooks.py +278 -0
- devupai-1.0.0a1.dist-info/METADATA +221 -0
- devupai-1.0.0a1.dist-info/RECORD +40 -0
- devupai-1.0.0a1.dist-info/WHEEL +4 -0
- devupai-1.0.0a1.dist-info/licenses/LICENSE +21 -0
devupai/_errors.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
"""Errors raised by the DEVUP AI API client, and the parsers for the response headers they carry."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
import time
|
|
9
|
+
from collections.abc import Callable, Mapping
|
|
10
|
+
from datetime import UTC
|
|
11
|
+
from email.utils import parsedate_to_datetime
|
|
12
|
+
from typing import Literal, TypeAlias, cast
|
|
13
|
+
|
|
14
|
+
#: Wall clock in epoch seconds. Read at call time, so tests can replace it.
|
|
15
|
+
_time: Callable[[], float] = time.time
|
|
16
|
+
|
|
17
|
+
_RETRY_AFTER_MS = re.compile(r"(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?", re.ASCII)
|
|
18
|
+
_RETRY_AFTER_SECONDS = re.compile(r"\d+(\.\d+)?", re.ASCII)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _get_header(headers: Mapping[str, str], name: str) -> str | None:
|
|
22
|
+
"""Returns the value of header ``name`` (lower case), looked up without regard to case."""
|
|
23
|
+
value = headers.get(name)
|
|
24
|
+
if value is not None:
|
|
25
|
+
return value
|
|
26
|
+
for key, item in headers.items():
|
|
27
|
+
if key.lower() == name:
|
|
28
|
+
return item
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _to_optional_str(value: object) -> str | None:
|
|
33
|
+
"""A string stays as is, a finite number becomes a string, anything else becomes ``None``."""
|
|
34
|
+
if isinstance(value, str):
|
|
35
|
+
return value
|
|
36
|
+
if isinstance(value, bool):
|
|
37
|
+
return None
|
|
38
|
+
if isinstance(value, int):
|
|
39
|
+
return str(value)
|
|
40
|
+
if isinstance(value, float):
|
|
41
|
+
if not math.isfinite(value):
|
|
42
|
+
return None
|
|
43
|
+
return str(int(value)) if value.is_integer() else str(value)
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def parse_retry_after_ms(headers: Mapping[str, str], now: float | None = None) -> float | None:
|
|
48
|
+
"""Reads the wait requested by the API before a new attempt, in milliseconds.
|
|
49
|
+
|
|
50
|
+
Uses ``retry-after-ms`` first, then ``Retry-After`` (seconds or an HTTP date). Header names are matched without
|
|
51
|
+
regard to case. ``now`` is the current time in epoch seconds and defaults to the wall clock. Returns ``None`` when
|
|
52
|
+
neither header contains a usable value.
|
|
53
|
+
"""
|
|
54
|
+
ms = _get_header(headers, "retry-after-ms")
|
|
55
|
+
if ms is not None:
|
|
56
|
+
trimmed_ms = ms.strip()
|
|
57
|
+
if trimmed_ms and _RETRY_AFTER_MS.fullmatch(trimmed_ms):
|
|
58
|
+
value = float(trimmed_ms)
|
|
59
|
+
if math.isfinite(value) and value >= 0:
|
|
60
|
+
return value
|
|
61
|
+
|
|
62
|
+
retry_after = _get_header(headers, "retry-after")
|
|
63
|
+
if retry_after is None:
|
|
64
|
+
return None
|
|
65
|
+
trimmed = retry_after.strip()
|
|
66
|
+
if not trimmed:
|
|
67
|
+
return None
|
|
68
|
+
if _RETRY_AFTER_SECONDS.fullmatch(trimmed):
|
|
69
|
+
return float(trimmed) * 1000.0
|
|
70
|
+
try:
|
|
71
|
+
date = parsedate_to_datetime(trimmed)
|
|
72
|
+
except (TypeError, ValueError, IndexError, OverflowError):
|
|
73
|
+
return None
|
|
74
|
+
if date.tzinfo is None:
|
|
75
|
+
date = date.replace(tzinfo=UTC)
|
|
76
|
+
try:
|
|
77
|
+
target = date.timestamp()
|
|
78
|
+
except (ValueError, OverflowError, OSError):
|
|
79
|
+
return None
|
|
80
|
+
current = _time() if now is None else now
|
|
81
|
+
return max(0.0, (target - current) * 1000.0)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def parse_warnings(headers: Mapping[str, str]) -> list[str]:
|
|
85
|
+
"""Parses the ``X-DEVUP-Warnings`` header: informational notices about how the request was handled.
|
|
86
|
+
|
|
87
|
+
Returns an empty list when the header is absent or empty.
|
|
88
|
+
"""
|
|
89
|
+
raw = _get_header(headers, "x-devup-warnings")
|
|
90
|
+
if not raw:
|
|
91
|
+
return []
|
|
92
|
+
return [part.strip() for part in raw.split(",") if part.strip()]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class DevupAPIError(Exception):
|
|
96
|
+
"""Error raised by the DEVUP AI API client.
|
|
97
|
+
|
|
98
|
+
``status`` is the HTTP status, or ``0`` when no response was received (connection error or timeout). The error
|
|
99
|
+
that led to this one, when there is one, is chained as ``__cause__``.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
status: int
|
|
103
|
+
"""HTTP status, or ``0`` when no response was received."""
|
|
104
|
+
message: str
|
|
105
|
+
"""Error message; ``str(error)`` gives the same text."""
|
|
106
|
+
type: str | None
|
|
107
|
+
"""Error type from the response body, when present."""
|
|
108
|
+
code: str | None
|
|
109
|
+
"""Error code from the response body, when present."""
|
|
110
|
+
param: str | None
|
|
111
|
+
"""Request parameter the error refers to, when present."""
|
|
112
|
+
request_id: str | None
|
|
113
|
+
"""Value of the ``x-request-id`` response header."""
|
|
114
|
+
client_request_id: str | None
|
|
115
|
+
"""Value of the ``x-client-request-id`` response header."""
|
|
116
|
+
retry_after: str | None
|
|
117
|
+
"""Raw value of the ``Retry-After`` response header."""
|
|
118
|
+
retry_after_ms: float | None
|
|
119
|
+
"""Wait requested by the API before a new attempt, in milliseconds."""
|
|
120
|
+
warnings: list[str]
|
|
121
|
+
"""Informational notices from the ``X-DEVUP-Warnings`` response header."""
|
|
122
|
+
headers: dict[str, str]
|
|
123
|
+
"""Response headers, with lower-cased names."""
|
|
124
|
+
|
|
125
|
+
def __init__(
|
|
126
|
+
self,
|
|
127
|
+
status: int,
|
|
128
|
+
message: str,
|
|
129
|
+
*,
|
|
130
|
+
error_type: object = None,
|
|
131
|
+
code: object = None,
|
|
132
|
+
param: object = None,
|
|
133
|
+
headers: Mapping[str, str] | None = None,
|
|
134
|
+
) -> None:
|
|
135
|
+
"""Creates the error from an HTTP status, a message, the fields of the ``error`` object and the headers."""
|
|
136
|
+
super().__init__(message)
|
|
137
|
+
self.status = status
|
|
138
|
+
self.message = message
|
|
139
|
+
self.type = _to_optional_str(error_type)
|
|
140
|
+
self.code = _to_optional_str(code)
|
|
141
|
+
self.param = param if isinstance(param, str) else None
|
|
142
|
+
self.headers = {} if headers is None else {key.lower(): value for key, value in headers.items()}
|
|
143
|
+
self.request_id = self.headers.get("x-request-id") or None
|
|
144
|
+
self.client_request_id = self.headers.get("x-client-request-id") or None
|
|
145
|
+
self.retry_after = self.headers.get("retry-after") or None
|
|
146
|
+
self.retry_after_ms = None if headers is None else parse_retry_after_ms(self.headers)
|
|
147
|
+
self.warnings = parse_warnings(self.headers)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class BadRequestError(DevupAPIError):
|
|
151
|
+
"""HTTP 400: the request is not valid as sent. ``code`` and ``param`` name the reason and the field."""
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class AuthenticationError(DevupAPIError):
|
|
155
|
+
"""HTTP 401: the API key is missing or not valid."""
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class PaymentRequiredError(DevupAPIError):
|
|
159
|
+
"""HTTP 402: the account balance (``code`` ``insufficient_balance``), or the budget of a scoped credential
|
|
160
|
+
(``budget_exhausted``), does not cover the request.
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class PermissionDeniedError(DevupAPIError):
|
|
165
|
+
"""HTTP 403: the API key is not permitted to perform this request."""
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class NotFoundError(DevupAPIError):
|
|
169
|
+
"""HTTP 404: the requested resource does not exist."""
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class ConflictError(DevupAPIError):
|
|
173
|
+
"""HTTP 409: the outcome of this request is not confirmed yet (``request_outcome_pending``).
|
|
174
|
+
|
|
175
|
+
Do not send it again: contact support with ``request_id``.
|
|
176
|
+
"""
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class PayloadTooLargeError(DevupAPIError):
|
|
180
|
+
"""HTTP 413: the request body is larger than the endpoint takes. Send a smaller body."""
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class UnsupportedMediaTypeError(DevupAPIError):
|
|
184
|
+
"""HTTP 415: the model does not accept the content type of the request.
|
|
185
|
+
|
|
186
|
+
Check the ``Content-Type`` header and the body format against the API reference.
|
|
187
|
+
"""
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class UnprocessableEntityError(DevupAPIError):
|
|
191
|
+
"""HTTP 422: the request is well formed, but a value in it cannot be processed. ``code`` and ``param`` name it."""
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class RateLimitError(DevupAPIError):
|
|
195
|
+
"""HTTP 429: too many requests. ``retry_after_ms`` gives the wait, when present."""
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class InternalServerError(DevupAPIError):
|
|
199
|
+
"""HTTP 500 or above.
|
|
200
|
+
|
|
201
|
+
After a 500 or 502 (``server_error``, ``DEVUP_COMPUTE_ERROR``) the request may already have been processed and
|
|
202
|
+
billed: check its outcome before sending it again.
|
|
203
|
+
"""
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class APIConnectionError(DevupAPIError):
|
|
207
|
+
"""No response was received from the API (``status`` is ``0``)."""
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
class APITimeoutError(APIConnectionError):
|
|
211
|
+
"""The request did not complete within its timeout (``status`` is ``0``)."""
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
_STATUS_CLASSES: dict[int, type[DevupAPIError]] = {
|
|
215
|
+
400: BadRequestError,
|
|
216
|
+
401: AuthenticationError,
|
|
217
|
+
402: PaymentRequiredError,
|
|
218
|
+
403: PermissionDeniedError,
|
|
219
|
+
404: NotFoundError,
|
|
220
|
+
409: ConflictError,
|
|
221
|
+
413: PayloadTooLargeError,
|
|
222
|
+
415: UnsupportedMediaTypeError,
|
|
223
|
+
422: UnprocessableEntityError,
|
|
224
|
+
429: RateLimitError,
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def make_api_error(
|
|
229
|
+
status: int,
|
|
230
|
+
message: str,
|
|
231
|
+
*,
|
|
232
|
+
error_type: object = None,
|
|
233
|
+
code: object = None,
|
|
234
|
+
param: object = None,
|
|
235
|
+
headers: Mapping[str, str] | None = None,
|
|
236
|
+
) -> DevupAPIError:
|
|
237
|
+
"""Creates the error for an HTTP status, using the matching subclass of :class:`DevupAPIError`.
|
|
238
|
+
|
|
239
|
+
Statuses without a subclass of their own give a plain :class:`DevupAPIError`. It never returns an
|
|
240
|
+
:class:`APIConnectionError`.
|
|
241
|
+
"""
|
|
242
|
+
cls = _STATUS_CLASSES.get(status)
|
|
243
|
+
if cls is None:
|
|
244
|
+
cls = InternalServerError if status >= 500 else DevupAPIError
|
|
245
|
+
return cls(status, message, error_type=error_type, code=code, param=param, headers=headers)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _as_record(value: object) -> dict[str, object] | None:
|
|
249
|
+
"""Returns ``value`` as a JSON object, or ``None`` when it is not one."""
|
|
250
|
+
if isinstance(value, dict):
|
|
251
|
+
return cast("dict[str, object]", value)
|
|
252
|
+
return None
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def error_from_body(status: int, text: str, headers: Mapping[str, str] | None) -> DevupAPIError:
|
|
256
|
+
"""Creates the error for a response that is not successful, from its status, body text and headers.
|
|
257
|
+
|
|
258
|
+
The message is ``error.message`` when the body is a JSON ``error`` object with a non-empty message, the ``error``
|
|
259
|
+
string when the body contains one, and the body text otherwise. A blank message becomes ``HTTP <status>``.
|
|
260
|
+
"""
|
|
261
|
+
message = text
|
|
262
|
+
error_type: str | None = None
|
|
263
|
+
code: str | int | float | None = None
|
|
264
|
+
param: str | None = None
|
|
265
|
+
if text:
|
|
266
|
+
try:
|
|
267
|
+
parsed: object = json.loads(text)
|
|
268
|
+
except (ValueError, RecursionError):
|
|
269
|
+
parsed = None
|
|
270
|
+
body = _as_record(parsed)
|
|
271
|
+
if body is not None:
|
|
272
|
+
error = body.get("error")
|
|
273
|
+
fields = _as_record(error)
|
|
274
|
+
if fields is not None:
|
|
275
|
+
error_message = fields.get("message")
|
|
276
|
+
if isinstance(error_message, str) and error_message:
|
|
277
|
+
message = error_message
|
|
278
|
+
raw_type = fields.get("type")
|
|
279
|
+
error_type = raw_type if isinstance(raw_type, str) else None
|
|
280
|
+
raw_code = fields.get("code")
|
|
281
|
+
if isinstance(raw_code, str | int | float) and not isinstance(raw_code, bool):
|
|
282
|
+
code = raw_code
|
|
283
|
+
raw_param = fields.get("param")
|
|
284
|
+
param = raw_param if isinstance(raw_param, str) else None
|
|
285
|
+
elif isinstance(error, str) and error:
|
|
286
|
+
message = error
|
|
287
|
+
if not message.strip():
|
|
288
|
+
message = f"HTTP {status}"
|
|
289
|
+
return make_api_error(status, message, error_type=error_type, code=code, param=param, headers=headers)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
DevupWebhookVerificationErrorReason: TypeAlias = Literal[
|
|
293
|
+
"malformed_header",
|
|
294
|
+
"timestamp_outside_tolerance",
|
|
295
|
+
"no_matching_signature",
|
|
296
|
+
"invalid_json",
|
|
297
|
+
]
|
|
298
|
+
"""Reasons a webhook signature check or payload construction can be rejected."""
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
class DevupWebhookVerificationError(Exception):
|
|
302
|
+
"""Error raised when a webhook payload cannot be verified or parsed.
|
|
303
|
+
|
|
304
|
+
``reason`` names the check that did not pass. The error that led to this one, when there is one, is chained as
|
|
305
|
+
``__cause__``.
|
|
306
|
+
"""
|
|
307
|
+
|
|
308
|
+
reason: DevupWebhookVerificationErrorReason
|
|
309
|
+
"""The check that did not pass."""
|
|
310
|
+
|
|
311
|
+
def __init__(self, reason: DevupWebhookVerificationErrorReason, message: str) -> None:
|
|
312
|
+
"""Creates the error from its reason and a message."""
|
|
313
|
+
super().__init__(message)
|
|
314
|
+
self.reason = reason
|
devupai/_response.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""The result of a request: the parsed data together with the HTTP response, and the binary results."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import warnings
|
|
7
|
+
from collections.abc import AsyncIterator, Iterator
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from types import TracebackType
|
|
10
|
+
from typing import Generic, Self, TypeVar
|
|
11
|
+
|
|
12
|
+
import anyio
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from devupai._errors import APIConnectionError, APITimeoutError, parse_warnings
|
|
16
|
+
|
|
17
|
+
T = TypeVar("T")
|
|
18
|
+
|
|
19
|
+
__all__ = ["APIResponse", "BinaryResponse", "AsyncBinaryResponse", "make_api_response"]
|
|
20
|
+
|
|
21
|
+
_READ_ERRORS = (httpx.TransportError, httpx.DecodingError)
|
|
22
|
+
_READ_TIMEOUT_MESSAGE = "The body of the response was not received in time."
|
|
23
|
+
_UNCLOSED_MESSAGE = (
|
|
24
|
+
"An AsyncBinaryResponse was dropped while its response was open. Use `async with`, or `await close()`, so the "
|
|
25
|
+
"connection is given back."
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _read_error(error: Exception, response: httpx.Response) -> APIConnectionError:
|
|
30
|
+
"""The error raised when reading a binary body does not complete: a timeout, or a connection error."""
|
|
31
|
+
if isinstance(error, httpx.TimeoutException):
|
|
32
|
+
return APITimeoutError(0, _READ_TIMEOUT_MESSAGE, headers=response.headers)
|
|
33
|
+
return APIConnectionError(0, f"Network error: {str(error) or 'unknown error'}", headers=response.headers)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _checked_chunks(response: httpx.Response, chunks: Iterator[bytes]) -> Iterator[bytes]:
|
|
37
|
+
"""``chunks``, with a read that does not complete raised as an SDK error; the response is then closed."""
|
|
38
|
+
try:
|
|
39
|
+
yield from chunks
|
|
40
|
+
except _READ_ERRORS as error:
|
|
41
|
+
response.close()
|
|
42
|
+
raise _read_error(error, response) from error
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
async def _checked_achunks(response: httpx.Response, chunks: AsyncIterator[bytes]) -> AsyncIterator[bytes]:
|
|
46
|
+
"""The async twin of :func:`_checked_chunks`."""
|
|
47
|
+
try:
|
|
48
|
+
async for chunk in chunks:
|
|
49
|
+
yield chunk
|
|
50
|
+
except _READ_ERRORS as error:
|
|
51
|
+
await response.aclose()
|
|
52
|
+
raise _read_error(error, response) from error
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass(frozen=True)
|
|
56
|
+
class APIResponse(Generic[T]):
|
|
57
|
+
"""The data of a response together with the HTTP response, its request ids and its warnings."""
|
|
58
|
+
|
|
59
|
+
data: T
|
|
60
|
+
"""The parsed response data."""
|
|
61
|
+
response: httpx.Response
|
|
62
|
+
"""The HTTP response. Its body has already been read, except for raw responses."""
|
|
63
|
+
request_id: str | None
|
|
64
|
+
"""Value of the ``x-request-id`` response header, or ``None`` when it is absent."""
|
|
65
|
+
client_request_id: str | None
|
|
66
|
+
"""Value of the ``x-client-request-id`` response header, or ``None`` when it is absent."""
|
|
67
|
+
warnings: list[str]
|
|
68
|
+
"""Informational notices from the ``X-DEVUP-Warnings`` response header."""
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def make_api_response(data: T, response: httpx.Response) -> APIResponse[T]:
|
|
72
|
+
"""Builds the :class:`APIResponse` of ``response`` carrying ``data``."""
|
|
73
|
+
return APIResponse(
|
|
74
|
+
data=data,
|
|
75
|
+
response=response,
|
|
76
|
+
request_id=response.headers.get("x-request-id"),
|
|
77
|
+
client_request_id=response.headers.get("x-client-request-id"),
|
|
78
|
+
warnings=parse_warnings(response.headers),
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class BinaryResponse:
|
|
83
|
+
"""A file answer of the API (an image, an audio clip, a video), with its body not read yet.
|
|
84
|
+
|
|
85
|
+
Read the bytes with :meth:`read`, :meth:`iter_bytes` or :meth:`write_to_file`. Close it with :meth:`close`, or
|
|
86
|
+
use it in a ``with`` block, when the body is not read to the end; a result that is dropped unread is closed when
|
|
87
|
+
it is collected. A read that does not complete raises :class:`~devupai.APIConnectionError`
|
|
88
|
+
(:class:`~devupai.APITimeoutError` when it times out).
|
|
89
|
+
|
|
90
|
+
Example::
|
|
91
|
+
|
|
92
|
+
with client.me.avatar() as avatar:
|
|
93
|
+
avatar.write_to_file("avatar.png")
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
response: httpx.Response
|
|
97
|
+
"""The HTTP response."""
|
|
98
|
+
status_code: int
|
|
99
|
+
"""The HTTP status (``304`` for an unchanged file asked for with ``If-None-Match``)."""
|
|
100
|
+
headers: httpx.Headers
|
|
101
|
+
"""The response headers (``content-type``, ``etag``, ...)."""
|
|
102
|
+
request_id: str | None
|
|
103
|
+
"""Value of the ``x-request-id`` response header, or ``None`` when it is absent."""
|
|
104
|
+
|
|
105
|
+
def __init__(self, response: httpx.Response) -> None:
|
|
106
|
+
self.response = response
|
|
107
|
+
self.status_code = response.status_code
|
|
108
|
+
self.headers = response.headers
|
|
109
|
+
self.request_id = response.headers.get("x-request-id")
|
|
110
|
+
|
|
111
|
+
def __repr__(self) -> str:
|
|
112
|
+
return f"{type(self).__name__}(status_code={self.status_code})"
|
|
113
|
+
|
|
114
|
+
def __del__(self) -> None:
|
|
115
|
+
# Gives the connection back when the result is dropped unread. ``response`` is missing only when
|
|
116
|
+
# ``__init__`` did not run to the end. Closing a closed response does nothing.
|
|
117
|
+
response: httpx.Response | None = vars(self).get("response")
|
|
118
|
+
if response is not None:
|
|
119
|
+
response.close()
|
|
120
|
+
|
|
121
|
+
def read(self) -> bytes:
|
|
122
|
+
"""Reads the whole body and returns its bytes. Calling it again returns the same bytes."""
|
|
123
|
+
try:
|
|
124
|
+
return self.response.read()
|
|
125
|
+
except _READ_ERRORS as error:
|
|
126
|
+
self.response.close()
|
|
127
|
+
raise _read_error(error, self.response) from error
|
|
128
|
+
|
|
129
|
+
def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
|
|
130
|
+
"""Yields the body in pieces: as they arrive, or of ``chunk_size`` bytes each (the last one can be shorter)."""
|
|
131
|
+
return _checked_chunks(self.response, self.response.iter_bytes(chunk_size))
|
|
132
|
+
|
|
133
|
+
def write_to_file(self, path: str | os.PathLike[str]) -> None:
|
|
134
|
+
"""Writes the body to the file at ``path``, replacing it when it exists, piece by piece."""
|
|
135
|
+
with open(path, "wb") as target:
|
|
136
|
+
for chunk in self.iter_bytes():
|
|
137
|
+
target.write(chunk)
|
|
138
|
+
|
|
139
|
+
def close(self) -> None:
|
|
140
|
+
"""Closes the response. Calling it again does nothing."""
|
|
141
|
+
self.response.close()
|
|
142
|
+
|
|
143
|
+
def __enter__(self) -> Self:
|
|
144
|
+
return self
|
|
145
|
+
|
|
146
|
+
def __exit__(
|
|
147
|
+
self,
|
|
148
|
+
exc_type: type[BaseException] | None,
|
|
149
|
+
exc: BaseException | None,
|
|
150
|
+
traceback: TracebackType | None,
|
|
151
|
+
) -> None:
|
|
152
|
+
self.close()
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class AsyncBinaryResponse:
|
|
156
|
+
"""The async twin of :class:`BinaryResponse`: a file answer of the API, with its body not read yet.
|
|
157
|
+
|
|
158
|
+
Read the bytes with :meth:`read`, :meth:`aiter_bytes` or :meth:`write_to_file`. Close it with :meth:`close`, or
|
|
159
|
+
use it in an ``async with`` block, when the body is not read to the end: a result dropped while still open
|
|
160
|
+
keeps its connection and emits a ``ResourceWarning``. A read that does not complete raises
|
|
161
|
+
:class:`~devupai.APIConnectionError` (:class:`~devupai.APITimeoutError` when it times out).
|
|
162
|
+
|
|
163
|
+
Example::
|
|
164
|
+
|
|
165
|
+
async with await client.me.avatar() as avatar:
|
|
166
|
+
await avatar.write_to_file("avatar.png")
|
|
167
|
+
"""
|
|
168
|
+
|
|
169
|
+
response: httpx.Response
|
|
170
|
+
"""The HTTP response."""
|
|
171
|
+
status_code: int
|
|
172
|
+
"""The HTTP status (``304`` for an unchanged file asked for with ``If-None-Match``)."""
|
|
173
|
+
headers: httpx.Headers
|
|
174
|
+
"""The response headers (``content-type``, ``etag``, ...)."""
|
|
175
|
+
request_id: str | None
|
|
176
|
+
"""Value of the ``x-request-id`` response header, or ``None`` when it is absent."""
|
|
177
|
+
|
|
178
|
+
def __init__(self, response: httpx.Response) -> None:
|
|
179
|
+
self.response = response
|
|
180
|
+
self.status_code = response.status_code
|
|
181
|
+
self.headers = response.headers
|
|
182
|
+
self.request_id = response.headers.get("x-request-id")
|
|
183
|
+
|
|
184
|
+
def __repr__(self) -> str:
|
|
185
|
+
return f"{type(self).__name__}(status_code={self.status_code})"
|
|
186
|
+
|
|
187
|
+
def __del__(self) -> None:
|
|
188
|
+
# An async close cannot run here, so an open response is reported instead. ``response`` is missing only
|
|
189
|
+
# when ``__init__`` did not run to the end.
|
|
190
|
+
response: httpx.Response | None = vars(self).get("response")
|
|
191
|
+
if response is not None and not response.is_closed:
|
|
192
|
+
warnings.warn(_UNCLOSED_MESSAGE, ResourceWarning, stacklevel=2, source=self)
|
|
193
|
+
|
|
194
|
+
async def read(self) -> bytes:
|
|
195
|
+
"""Reads the whole body and returns its bytes. Calling it again returns the same bytes."""
|
|
196
|
+
try:
|
|
197
|
+
return await self.response.aread()
|
|
198
|
+
except _READ_ERRORS as error:
|
|
199
|
+
await self.response.aclose()
|
|
200
|
+
raise _read_error(error, self.response) from error
|
|
201
|
+
|
|
202
|
+
def aiter_bytes(self, chunk_size: int | None = None) -> AsyncIterator[bytes]:
|
|
203
|
+
"""Yields the body in pieces: as they arrive, or of ``chunk_size`` bytes each (the last one can be shorter)."""
|
|
204
|
+
return _checked_achunks(self.response, self.response.aiter_bytes(chunk_size))
|
|
205
|
+
|
|
206
|
+
async def write_to_file(self, path: str | os.PathLike[str]) -> None:
|
|
207
|
+
"""Writes the body to the file at ``path``, replacing it when it exists, piece by piece."""
|
|
208
|
+
async with await anyio.open_file(path, "wb") as target:
|
|
209
|
+
async for chunk in self.aiter_bytes():
|
|
210
|
+
await target.write(chunk)
|
|
211
|
+
|
|
212
|
+
async def close(self) -> None:
|
|
213
|
+
"""Closes the response. Calling it again does nothing."""
|
|
214
|
+
await self.response.aclose()
|
|
215
|
+
|
|
216
|
+
async def __aenter__(self) -> Self:
|
|
217
|
+
return self
|
|
218
|
+
|
|
219
|
+
async def __aexit__(
|
|
220
|
+
self,
|
|
221
|
+
exc_type: type[BaseException] | None,
|
|
222
|
+
exc: BaseException | None,
|
|
223
|
+
traceback: TracebackType | None,
|
|
224
|
+
) -> None:
|
|
225
|
+
await self.close()
|