teleleo 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.
- teleleo/__init__.py +61 -0
- teleleo/_base_client.py +447 -0
- teleleo/_client.py +176 -0
- teleleo/_exceptions.py +201 -0
- teleleo/_models.py +135 -0
- teleleo/_pagination.py +133 -0
- teleleo/_resource.py +22 -0
- teleleo/_types.py +36 -0
- teleleo/_utils.py +90 -0
- teleleo/_version.py +1 -0
- teleleo/py.typed +0 -0
- teleleo/resources/__init__.py +205 -0
- teleleo/resources/call_scenarios.py +553 -0
- teleleo/resources/calls.py +381 -0
- teleleo/resources/contact_groups.py +366 -0
- teleleo/resources/contacts.py +497 -0
- teleleo/resources/dongles.py +1103 -0
- teleleo/resources/files.py +287 -0
- teleleo/resources/follow_up_sms_settings.py +388 -0
- teleleo/resources/mailings.py +807 -0
- teleleo/resources/public_vpn.py +245 -0
- teleleo/resources/redirections.py +408 -0
- teleleo/resources/sip_users.py +141 -0
- teleleo/resources/sms.py +807 -0
- teleleo/resources/socks_proxies.py +338 -0
- teleleo/resources/ussd.py +344 -0
- teleleo/types/__init__.py +127 -0
- teleleo/types/enums.py +282 -0
- teleleo/types/models.py +1075 -0
- teleleo/types/params.py +89 -0
- teleleo-0.1.0.dist-info/METADATA +215 -0
- teleleo-0.1.0.dist-info/RECORD +34 -0
- teleleo-0.1.0.dist-info/WHEEL +4 -0
- teleleo-0.1.0.dist-info/licenses/LICENSE +21 -0
teleleo/__init__.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""The official Python library for the Teleleo API.
|
|
2
|
+
|
|
3
|
+
::
|
|
4
|
+
|
|
5
|
+
from teleleo import Teleleo
|
|
6
|
+
|
|
7
|
+
client = Teleleo() # reads TELELEO_API_KEY
|
|
8
|
+
for dongle in client.dongles.list():
|
|
9
|
+
print(dongle.dongle_id, dongle.name)
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from . import types
|
|
13
|
+
from ._base_client import DEFAULT_BASE_URL, DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT
|
|
14
|
+
from ._client import AsyncTeleleo, Teleleo
|
|
15
|
+
from ._exceptions import (
|
|
16
|
+
APIConnectionError,
|
|
17
|
+
APIError,
|
|
18
|
+
APIResponseValidationError,
|
|
19
|
+
APIStatusError,
|
|
20
|
+
APITimeoutError,
|
|
21
|
+
AuthenticationError,
|
|
22
|
+
BadRequestError,
|
|
23
|
+
ConflictError,
|
|
24
|
+
InternalServerError,
|
|
25
|
+
NotFoundError,
|
|
26
|
+
PermissionDeniedError,
|
|
27
|
+
RateLimitError,
|
|
28
|
+
TeleleoError,
|
|
29
|
+
)
|
|
30
|
+
from ._models import BaseModel
|
|
31
|
+
from ._pagination import AsyncPage, SyncPage
|
|
32
|
+
from ._types import NOT_GIVEN, NotGiven
|
|
33
|
+
from ._version import __version__
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"Teleleo",
|
|
37
|
+
"AsyncTeleleo",
|
|
38
|
+
"types",
|
|
39
|
+
"SyncPage",
|
|
40
|
+
"AsyncPage",
|
|
41
|
+
"BaseModel",
|
|
42
|
+
"NOT_GIVEN",
|
|
43
|
+
"NotGiven",
|
|
44
|
+
"DEFAULT_BASE_URL",
|
|
45
|
+
"DEFAULT_TIMEOUT",
|
|
46
|
+
"DEFAULT_MAX_RETRIES",
|
|
47
|
+
"TeleleoError",
|
|
48
|
+
"APIError",
|
|
49
|
+
"APIConnectionError",
|
|
50
|
+
"APITimeoutError",
|
|
51
|
+
"APIResponseValidationError",
|
|
52
|
+
"APIStatusError",
|
|
53
|
+
"BadRequestError",
|
|
54
|
+
"AuthenticationError",
|
|
55
|
+
"PermissionDeniedError",
|
|
56
|
+
"NotFoundError",
|
|
57
|
+
"ConflictError",
|
|
58
|
+
"RateLimitError",
|
|
59
|
+
"InternalServerError",
|
|
60
|
+
"__version__",
|
|
61
|
+
]
|
teleleo/_base_client.py
ADDED
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import email.utils
|
|
5
|
+
import random
|
|
6
|
+
import time
|
|
7
|
+
from typing import Any, Dict, List, Mapping, Optional, Tuple, Type, TypeVar, Union
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from ._exceptions import APIConnectionError, APIResponseValidationError, APITimeoutError, make_status_error
|
|
12
|
+
from ._models import construct_type
|
|
13
|
+
from ._pagination import AsyncPage, SyncPage
|
|
14
|
+
from ._types import NOT_GIVEN, Body, Headers, NotGiven, Query, Timeout
|
|
15
|
+
from ._utils import build_body, build_query
|
|
16
|
+
from ._version import __version__
|
|
17
|
+
|
|
18
|
+
__all__ = ["SyncAPIClient", "AsyncAPIClient", "DEFAULT_BASE_URL", "DEFAULT_TIMEOUT", "DEFAULT_MAX_RETRIES"]
|
|
19
|
+
|
|
20
|
+
DEFAULT_BASE_URL = "https://app.teleleo.com/react_api"
|
|
21
|
+
DEFAULT_TIMEOUT = httpx.Timeout(60.0, connect=10.0)
|
|
22
|
+
DEFAULT_MAX_RETRIES = 2
|
|
23
|
+
|
|
24
|
+
INITIAL_RETRY_DELAY = 0.5
|
|
25
|
+
MAX_RETRY_DELAY = 8.0
|
|
26
|
+
MAX_RETRY_AFTER = 60.0
|
|
27
|
+
|
|
28
|
+
_IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "PUT", "DELETE"})
|
|
29
|
+
# The server refused the request before acting on it: safe to repeat for any method.
|
|
30
|
+
_RETRY_ANY_METHOD = frozenset({429})
|
|
31
|
+
# The outcome is unknown: repeat only requests that are safe to repeat.
|
|
32
|
+
_RETRY_IDEMPOTENT = frozenset({408, 502, 503, 504})
|
|
33
|
+
# Nothing reached the server.
|
|
34
|
+
_NOT_SENT_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout, httpx.PoolTimeout)
|
|
35
|
+
|
|
36
|
+
_T = TypeVar("_T")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _clean_query(query: Optional[Mapping[str, object]]) -> Dict[str, Any]:
|
|
40
|
+
out: Dict[str, Any] = {}
|
|
41
|
+
for key, value in (query or {}).items():
|
|
42
|
+
if value is None or isinstance(value, NotGiven):
|
|
43
|
+
continue
|
|
44
|
+
if not isinstance(value, (str, bytes, Mapping)) and hasattr(value, "__iter__"):
|
|
45
|
+
value = list(value) # a generator would be used up by the first page
|
|
46
|
+
out[key] = value
|
|
47
|
+
return out
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class _BaseClient:
|
|
51
|
+
api_key: str
|
|
52
|
+
base_url: str
|
|
53
|
+
timeout: Timeout
|
|
54
|
+
max_retries: int
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
*,
|
|
59
|
+
api_key: str,
|
|
60
|
+
base_url: Union[str, httpx.URL],
|
|
61
|
+
timeout: Timeout,
|
|
62
|
+
max_retries: int,
|
|
63
|
+
default_headers: Optional[Headers],
|
|
64
|
+
) -> None:
|
|
65
|
+
self.api_key = api_key
|
|
66
|
+
self.base_url = str(base_url).rstrip("/")
|
|
67
|
+
self.timeout = timeout
|
|
68
|
+
self.max_retries = max_retries
|
|
69
|
+
self._custom_headers: Dict[str, str] = dict(default_headers or {})
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def default_headers(self) -> Dict[str, str]:
|
|
73
|
+
return {
|
|
74
|
+
"Accept": "application/json",
|
|
75
|
+
"User-Agent": f"teleleo-python/{__version__}",
|
|
76
|
+
"auth-key": self.api_key,
|
|
77
|
+
**self._custom_headers,
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
def _prepare(
|
|
81
|
+
self,
|
|
82
|
+
query: Optional[Query],
|
|
83
|
+
body: Optional[Body],
|
|
84
|
+
extra_query: Optional[Query],
|
|
85
|
+
extra_body: Optional[Body],
|
|
86
|
+
) -> Tuple[List[Tuple[str, str]], Optional[Dict[str, Any]]]:
|
|
87
|
+
params = build_query(query, extra_query)
|
|
88
|
+
json_body = build_body(body, extra_body) if body is not None or extra_body is not None else None
|
|
89
|
+
return params, json_body
|
|
90
|
+
|
|
91
|
+
def _headers(self, extra_headers: Optional[Headers], accept: Optional[str]) -> Dict[str, str]:
|
|
92
|
+
headers = self.default_headers
|
|
93
|
+
if accept:
|
|
94
|
+
headers["Accept"] = accept
|
|
95
|
+
if extra_headers:
|
|
96
|
+
headers.update(extra_headers)
|
|
97
|
+
return headers
|
|
98
|
+
|
|
99
|
+
def _timeout(self, timeout: Union[Timeout, NotGiven]) -> Timeout:
|
|
100
|
+
return self.timeout if isinstance(timeout, NotGiven) else timeout
|
|
101
|
+
|
|
102
|
+
@staticmethod
|
|
103
|
+
def _should_retry_status(method: str, status: int) -> bool:
|
|
104
|
+
return status in _RETRY_ANY_METHOD or (status in _RETRY_IDEMPOTENT and method in _IDEMPOTENT_METHODS)
|
|
105
|
+
|
|
106
|
+
@staticmethod
|
|
107
|
+
def _should_retry_exception(method: str, exc: Exception) -> bool:
|
|
108
|
+
return isinstance(exc, _NOT_SENT_ERRORS) or method in _IDEMPOTENT_METHODS
|
|
109
|
+
|
|
110
|
+
@staticmethod
|
|
111
|
+
def _retry_delay(attempt: int, response: Optional[httpx.Response]) -> float:
|
|
112
|
+
if response is not None:
|
|
113
|
+
header = response.headers.get("retry-after")
|
|
114
|
+
if header:
|
|
115
|
+
seconds: float
|
|
116
|
+
try:
|
|
117
|
+
seconds = float(header)
|
|
118
|
+
except ValueError:
|
|
119
|
+
parsed = email.utils.parsedate_tz(header)
|
|
120
|
+
seconds = float(email.utils.mktime_tz(parsed) - time.time()) if parsed else -1.0
|
|
121
|
+
if 0 <= seconds <= MAX_RETRY_AFTER:
|
|
122
|
+
return seconds
|
|
123
|
+
delay = min(INITIAL_RETRY_DELAY * (2.0**attempt), MAX_RETRY_DELAY)
|
|
124
|
+
return delay * (1 - 0.25 * random.random())
|
|
125
|
+
|
|
126
|
+
@staticmethod
|
|
127
|
+
def _decode_data(response: httpx.Response) -> Any:
|
|
128
|
+
try:
|
|
129
|
+
payload = response.json()
|
|
130
|
+
except ValueError:
|
|
131
|
+
content_type = response.headers.get("content-type") or "no content type"
|
|
132
|
+
raise APIResponseValidationError(
|
|
133
|
+
response, message=f"Expected a JSON answer from {response.request.url.path}, got {content_type}"
|
|
134
|
+
) from None
|
|
135
|
+
if isinstance(payload, dict) and "data" in payload:
|
|
136
|
+
return payload["data"]
|
|
137
|
+
return payload
|
|
138
|
+
|
|
139
|
+
@staticmethod
|
|
140
|
+
def _page_items(data: Any, item_key: str, item_type: Type[_T]) -> Tuple[List[_T], Optional[int]]:
|
|
141
|
+
raw: Any = []
|
|
142
|
+
total: Any = None
|
|
143
|
+
if isinstance(data, dict):
|
|
144
|
+
raw = data.get(item_key) or []
|
|
145
|
+
total = data.get("total_count")
|
|
146
|
+
elif isinstance(data, list):
|
|
147
|
+
raw = data
|
|
148
|
+
items = construct_type(List[item_type], raw) # type: ignore[valid-type]
|
|
149
|
+
if not isinstance(items, list):
|
|
150
|
+
items = []
|
|
151
|
+
return items, total if isinstance(total, int) and not isinstance(total, bool) else None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class SyncAPIClient(_BaseClient):
|
|
155
|
+
_http: httpx.Client
|
|
156
|
+
|
|
157
|
+
def __init__(
|
|
158
|
+
self,
|
|
159
|
+
*,
|
|
160
|
+
api_key: str,
|
|
161
|
+
base_url: Union[str, httpx.URL],
|
|
162
|
+
timeout: Timeout,
|
|
163
|
+
max_retries: int,
|
|
164
|
+
default_headers: Optional[Headers],
|
|
165
|
+
http_client: Optional[httpx.Client],
|
|
166
|
+
) -> None:
|
|
167
|
+
super().__init__(
|
|
168
|
+
api_key=api_key,
|
|
169
|
+
base_url=base_url,
|
|
170
|
+
timeout=timeout,
|
|
171
|
+
max_retries=max_retries,
|
|
172
|
+
default_headers=default_headers,
|
|
173
|
+
)
|
|
174
|
+
self._owns_http = http_client is None
|
|
175
|
+
self._http = http_client or httpx.Client(timeout=timeout, follow_redirects=True)
|
|
176
|
+
|
|
177
|
+
def close(self) -> None:
|
|
178
|
+
"""Close the underlying HTTP connections."""
|
|
179
|
+
if self._owns_http:
|
|
180
|
+
self._http.close()
|
|
181
|
+
|
|
182
|
+
def _send(
|
|
183
|
+
self,
|
|
184
|
+
method: str,
|
|
185
|
+
path: str,
|
|
186
|
+
*,
|
|
187
|
+
query: Optional[Query] = None,
|
|
188
|
+
body: Optional[Body] = None,
|
|
189
|
+
extra_headers: Optional[Headers] = None,
|
|
190
|
+
extra_query: Optional[Query] = None,
|
|
191
|
+
extra_body: Optional[Body] = None,
|
|
192
|
+
timeout: Union[Timeout, NotGiven] = NOT_GIVEN,
|
|
193
|
+
accept: Optional[str] = None,
|
|
194
|
+
) -> httpx.Response:
|
|
195
|
+
params, json_body = self._prepare(query, body, extra_query, extra_body)
|
|
196
|
+
headers = self._headers(extra_headers, accept)
|
|
197
|
+
attempt = 0
|
|
198
|
+
while True:
|
|
199
|
+
request = self._http.build_request(
|
|
200
|
+
method,
|
|
201
|
+
self.base_url + path,
|
|
202
|
+
params=tuple(params) if params else None,
|
|
203
|
+
json=json_body,
|
|
204
|
+
headers=headers,
|
|
205
|
+
timeout=self._timeout(timeout),
|
|
206
|
+
)
|
|
207
|
+
try:
|
|
208
|
+
response = self._http.send(request)
|
|
209
|
+
except httpx.TimeoutException as exc:
|
|
210
|
+
if attempt < self.max_retries and self._should_retry_exception(method, exc):
|
|
211
|
+
time.sleep(self._retry_delay(attempt, None))
|
|
212
|
+
attempt += 1
|
|
213
|
+
continue
|
|
214
|
+
raise APITimeoutError(request) from exc
|
|
215
|
+
except httpx.TransportError as exc:
|
|
216
|
+
if attempt < self.max_retries and self._should_retry_exception(method, exc):
|
|
217
|
+
time.sleep(self._retry_delay(attempt, None))
|
|
218
|
+
attempt += 1
|
|
219
|
+
continue
|
|
220
|
+
raise APIConnectionError(request=request) from exc
|
|
221
|
+
|
|
222
|
+
if response.is_success:
|
|
223
|
+
return response
|
|
224
|
+
if attempt < self.max_retries and self._should_retry_status(method, response.status_code):
|
|
225
|
+
delay = self._retry_delay(attempt, response)
|
|
226
|
+
response.close()
|
|
227
|
+
time.sleep(delay)
|
|
228
|
+
attempt += 1
|
|
229
|
+
continue
|
|
230
|
+
response.read()
|
|
231
|
+
raise make_status_error(response)
|
|
232
|
+
|
|
233
|
+
def _request(
|
|
234
|
+
self,
|
|
235
|
+
method: str,
|
|
236
|
+
path: str,
|
|
237
|
+
*,
|
|
238
|
+
query: Optional[Query] = None,
|
|
239
|
+
body: Optional[Body] = None,
|
|
240
|
+
extra_headers: Optional[Headers] = None,
|
|
241
|
+
extra_query: Optional[Query] = None,
|
|
242
|
+
extra_body: Optional[Body] = None,
|
|
243
|
+
timeout: Union[Timeout, NotGiven] = NOT_GIVEN,
|
|
244
|
+
) -> Any:
|
|
245
|
+
response = self._send(
|
|
246
|
+
method,
|
|
247
|
+
path,
|
|
248
|
+
query=query,
|
|
249
|
+
body=body,
|
|
250
|
+
extra_headers=extra_headers,
|
|
251
|
+
extra_query=extra_query,
|
|
252
|
+
extra_body=extra_body,
|
|
253
|
+
timeout=timeout,
|
|
254
|
+
)
|
|
255
|
+
return self._decode_data(response)
|
|
256
|
+
|
|
257
|
+
def _request_bytes(
|
|
258
|
+
self,
|
|
259
|
+
method: str,
|
|
260
|
+
path: str,
|
|
261
|
+
*,
|
|
262
|
+
extra_headers: Optional[Headers] = None,
|
|
263
|
+
extra_query: Optional[Query] = None,
|
|
264
|
+
timeout: Union[Timeout, NotGiven] = NOT_GIVEN,
|
|
265
|
+
) -> bytes:
|
|
266
|
+
response = self._send(
|
|
267
|
+
method, path, extra_headers=extra_headers, extra_query=extra_query, timeout=timeout, accept="*/*"
|
|
268
|
+
)
|
|
269
|
+
return response.content
|
|
270
|
+
|
|
271
|
+
def _get_page(
|
|
272
|
+
self,
|
|
273
|
+
path: str,
|
|
274
|
+
*,
|
|
275
|
+
query: Query,
|
|
276
|
+
item_key: str,
|
|
277
|
+
item_type: Type[_T],
|
|
278
|
+
extra_headers: Optional[Headers] = None,
|
|
279
|
+
extra_query: Optional[Query] = None,
|
|
280
|
+
timeout: Union[Timeout, NotGiven] = NOT_GIVEN,
|
|
281
|
+
) -> SyncPage[_T]:
|
|
282
|
+
clean = _clean_query(query)
|
|
283
|
+
data = self._request(
|
|
284
|
+
"GET", path, query=clean, extra_headers=extra_headers, extra_query=extra_query, timeout=timeout
|
|
285
|
+
)
|
|
286
|
+
items, total = self._page_items(data, item_key, item_type)
|
|
287
|
+
|
|
288
|
+
def fetch(next_query: Dict[str, Any]) -> SyncPage[_T]:
|
|
289
|
+
return self._get_page(
|
|
290
|
+
path,
|
|
291
|
+
query=next_query,
|
|
292
|
+
item_key=item_key,
|
|
293
|
+
item_type=item_type,
|
|
294
|
+
extra_headers=extra_headers,
|
|
295
|
+
extra_query=extra_query,
|
|
296
|
+
timeout=timeout,
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
return SyncPage(items=items, total_count=total, query=clean, fetch=fetch)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
class AsyncAPIClient(_BaseClient):
|
|
303
|
+
_http: httpx.AsyncClient
|
|
304
|
+
|
|
305
|
+
def __init__(
|
|
306
|
+
self,
|
|
307
|
+
*,
|
|
308
|
+
api_key: str,
|
|
309
|
+
base_url: Union[str, httpx.URL],
|
|
310
|
+
timeout: Timeout,
|
|
311
|
+
max_retries: int,
|
|
312
|
+
default_headers: Optional[Headers],
|
|
313
|
+
http_client: Optional[httpx.AsyncClient],
|
|
314
|
+
) -> None:
|
|
315
|
+
super().__init__(
|
|
316
|
+
api_key=api_key,
|
|
317
|
+
base_url=base_url,
|
|
318
|
+
timeout=timeout,
|
|
319
|
+
max_retries=max_retries,
|
|
320
|
+
default_headers=default_headers,
|
|
321
|
+
)
|
|
322
|
+
self._owns_http = http_client is None
|
|
323
|
+
self._http = http_client or httpx.AsyncClient(timeout=timeout, follow_redirects=True)
|
|
324
|
+
|
|
325
|
+
async def close(self) -> None:
|
|
326
|
+
"""Close the underlying HTTP connections."""
|
|
327
|
+
if self._owns_http:
|
|
328
|
+
await self._http.aclose()
|
|
329
|
+
|
|
330
|
+
async def _send(
|
|
331
|
+
self,
|
|
332
|
+
method: str,
|
|
333
|
+
path: str,
|
|
334
|
+
*,
|
|
335
|
+
query: Optional[Query] = None,
|
|
336
|
+
body: Optional[Body] = None,
|
|
337
|
+
extra_headers: Optional[Headers] = None,
|
|
338
|
+
extra_query: Optional[Query] = None,
|
|
339
|
+
extra_body: Optional[Body] = None,
|
|
340
|
+
timeout: Union[Timeout, NotGiven] = NOT_GIVEN,
|
|
341
|
+
accept: Optional[str] = None,
|
|
342
|
+
) -> httpx.Response:
|
|
343
|
+
params, json_body = self._prepare(query, body, extra_query, extra_body)
|
|
344
|
+
headers = self._headers(extra_headers, accept)
|
|
345
|
+
attempt = 0
|
|
346
|
+
while True:
|
|
347
|
+
request = self._http.build_request(
|
|
348
|
+
method,
|
|
349
|
+
self.base_url + path,
|
|
350
|
+
params=tuple(params) if params else None,
|
|
351
|
+
json=json_body,
|
|
352
|
+
headers=headers,
|
|
353
|
+
timeout=self._timeout(timeout),
|
|
354
|
+
)
|
|
355
|
+
try:
|
|
356
|
+
response = await self._http.send(request)
|
|
357
|
+
except httpx.TimeoutException as exc:
|
|
358
|
+
if attempt < self.max_retries and self._should_retry_exception(method, exc):
|
|
359
|
+
await asyncio.sleep(self._retry_delay(attempt, None))
|
|
360
|
+
attempt += 1
|
|
361
|
+
continue
|
|
362
|
+
raise APITimeoutError(request) from exc
|
|
363
|
+
except httpx.TransportError as exc:
|
|
364
|
+
if attempt < self.max_retries and self._should_retry_exception(method, exc):
|
|
365
|
+
await asyncio.sleep(self._retry_delay(attempt, None))
|
|
366
|
+
attempt += 1
|
|
367
|
+
continue
|
|
368
|
+
raise APIConnectionError(request=request) from exc
|
|
369
|
+
|
|
370
|
+
if response.is_success:
|
|
371
|
+
return response
|
|
372
|
+
if attempt < self.max_retries and self._should_retry_status(method, response.status_code):
|
|
373
|
+
delay = self._retry_delay(attempt, response)
|
|
374
|
+
await response.aclose()
|
|
375
|
+
await asyncio.sleep(delay)
|
|
376
|
+
attempt += 1
|
|
377
|
+
continue
|
|
378
|
+
await response.aread()
|
|
379
|
+
raise make_status_error(response)
|
|
380
|
+
|
|
381
|
+
async def _request(
|
|
382
|
+
self,
|
|
383
|
+
method: str,
|
|
384
|
+
path: str,
|
|
385
|
+
*,
|
|
386
|
+
query: Optional[Query] = None,
|
|
387
|
+
body: Optional[Body] = None,
|
|
388
|
+
extra_headers: Optional[Headers] = None,
|
|
389
|
+
extra_query: Optional[Query] = None,
|
|
390
|
+
extra_body: Optional[Body] = None,
|
|
391
|
+
timeout: Union[Timeout, NotGiven] = NOT_GIVEN,
|
|
392
|
+
) -> Any:
|
|
393
|
+
response = await self._send(
|
|
394
|
+
method,
|
|
395
|
+
path,
|
|
396
|
+
query=query,
|
|
397
|
+
body=body,
|
|
398
|
+
extra_headers=extra_headers,
|
|
399
|
+
extra_query=extra_query,
|
|
400
|
+
extra_body=extra_body,
|
|
401
|
+
timeout=timeout,
|
|
402
|
+
)
|
|
403
|
+
return self._decode_data(response)
|
|
404
|
+
|
|
405
|
+
async def _request_bytes(
|
|
406
|
+
self,
|
|
407
|
+
method: str,
|
|
408
|
+
path: str,
|
|
409
|
+
*,
|
|
410
|
+
extra_headers: Optional[Headers] = None,
|
|
411
|
+
extra_query: Optional[Query] = None,
|
|
412
|
+
timeout: Union[Timeout, NotGiven] = NOT_GIVEN,
|
|
413
|
+
) -> bytes:
|
|
414
|
+
response = await self._send(
|
|
415
|
+
method, path, extra_headers=extra_headers, extra_query=extra_query, timeout=timeout, accept="*/*"
|
|
416
|
+
)
|
|
417
|
+
return response.content
|
|
418
|
+
|
|
419
|
+
async def _get_page(
|
|
420
|
+
self,
|
|
421
|
+
path: str,
|
|
422
|
+
*,
|
|
423
|
+
query: Query,
|
|
424
|
+
item_key: str,
|
|
425
|
+
item_type: Type[_T],
|
|
426
|
+
extra_headers: Optional[Headers] = None,
|
|
427
|
+
extra_query: Optional[Query] = None,
|
|
428
|
+
timeout: Union[Timeout, NotGiven] = NOT_GIVEN,
|
|
429
|
+
) -> AsyncPage[_T]:
|
|
430
|
+
clean = _clean_query(query)
|
|
431
|
+
data = await self._request(
|
|
432
|
+
"GET", path, query=clean, extra_headers=extra_headers, extra_query=extra_query, timeout=timeout
|
|
433
|
+
)
|
|
434
|
+
items, total = self._page_items(data, item_key, item_type)
|
|
435
|
+
|
|
436
|
+
async def fetch(next_query: Dict[str, Any]) -> AsyncPage[_T]:
|
|
437
|
+
return await self._get_page(
|
|
438
|
+
path,
|
|
439
|
+
query=next_query,
|
|
440
|
+
item_key=item_key,
|
|
441
|
+
item_type=item_type,
|
|
442
|
+
extra_headers=extra_headers,
|
|
443
|
+
extra_query=extra_query,
|
|
444
|
+
timeout=timeout,
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
return AsyncPage(items=items, total_count=total, query=clean, fetch=fetch)
|
teleleo/_client.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from types import TracebackType
|
|
5
|
+
from typing import Optional, Type, Union
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from ._base_client import DEFAULT_BASE_URL, DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT, AsyncAPIClient, SyncAPIClient
|
|
10
|
+
from ._exceptions import TeleleoError
|
|
11
|
+
from ._types import NOT_GIVEN, Headers, NotGiven, Timeout
|
|
12
|
+
from .resources import AsyncResources, SyncResources
|
|
13
|
+
|
|
14
|
+
__all__ = ["Teleleo", "AsyncTeleleo"]
|
|
15
|
+
|
|
16
|
+
_MISSING_KEY = (
|
|
17
|
+
"The API key is not set: pass api_key to the client or set the TELELEO_API_KEY environment variable. "
|
|
18
|
+
"The key is in the Teleleo cabinet, Settings - API key."
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _resolve(
|
|
23
|
+
api_key: Optional[str], base_url: Union[str, httpx.URL, None], timeout: Union[Timeout, NotGiven]
|
|
24
|
+
) -> tuple[str, str, Timeout]:
|
|
25
|
+
key = api_key if api_key is not None else os.environ.get("TELELEO_API_KEY")
|
|
26
|
+
if not key:
|
|
27
|
+
raise TeleleoError(_MISSING_KEY)
|
|
28
|
+
url = str(base_url) if base_url is not None else (os.environ.get("TELELEO_BASE_URL") or DEFAULT_BASE_URL)
|
|
29
|
+
return key, url, DEFAULT_TIMEOUT if isinstance(timeout, NotGiven) else timeout
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Teleleo(SyncResources, SyncAPIClient):
|
|
33
|
+
"""Client for the Teleleo API.
|
|
34
|
+
|
|
35
|
+
::
|
|
36
|
+
|
|
37
|
+
from teleleo import Teleleo
|
|
38
|
+
|
|
39
|
+
client = Teleleo() # reads TELELEO_API_KEY
|
|
40
|
+
for dongle in client.dongles.list():
|
|
41
|
+
print(dongle.dongle_id, dongle.name)
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
api_key: The API key from the Teleleo cabinet (Settings - API key). Defaults to ``TELELEO_API_KEY``.
|
|
45
|
+
base_url: Defaults to ``TELELEO_BASE_URL``, then to ``https://app.teleleo.com/react_api``.
|
|
46
|
+
timeout: Seconds or an ``httpx.Timeout``; 60 seconds by default.
|
|
47
|
+
max_retries: How many times to repeat a request that failed for a transient reason; 2 by default.
|
|
48
|
+
Requests that create something (POST) are repeated only when the server could not have acted on them.
|
|
49
|
+
default_headers: Headers to send with every request.
|
|
50
|
+
http_client: Your own ``httpx.Client``, for proxies or custom transports.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(
|
|
54
|
+
self,
|
|
55
|
+
*,
|
|
56
|
+
api_key: Optional[str] = None,
|
|
57
|
+
base_url: Union[str, httpx.URL, None] = None,
|
|
58
|
+
timeout: Union[Timeout, NotGiven] = NOT_GIVEN,
|
|
59
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
60
|
+
default_headers: Optional[Headers] = None,
|
|
61
|
+
http_client: Optional[httpx.Client] = None,
|
|
62
|
+
) -> None:
|
|
63
|
+
key, url, resolved_timeout = _resolve(api_key, base_url, timeout)
|
|
64
|
+
super().__init__(
|
|
65
|
+
api_key=key,
|
|
66
|
+
base_url=url,
|
|
67
|
+
timeout=resolved_timeout,
|
|
68
|
+
max_retries=max_retries,
|
|
69
|
+
default_headers=default_headers,
|
|
70
|
+
http_client=http_client,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
def with_options(
|
|
74
|
+
self,
|
|
75
|
+
*,
|
|
76
|
+
api_key: Optional[str] = None,
|
|
77
|
+
base_url: Union[str, httpx.URL, None] = None,
|
|
78
|
+
timeout: Union[Timeout, NotGiven] = NOT_GIVEN,
|
|
79
|
+
max_retries: Optional[int] = None,
|
|
80
|
+
default_headers: Optional[Headers] = None,
|
|
81
|
+
) -> Teleleo:
|
|
82
|
+
"""A copy of the client with some options changed; it shares the connection pool with this one.
|
|
83
|
+
|
|
84
|
+
::
|
|
85
|
+
|
|
86
|
+
client.with_options(timeout=5, max_retries=0).dongles.list()
|
|
87
|
+
"""
|
|
88
|
+
return Teleleo(
|
|
89
|
+
api_key=api_key or self.api_key,
|
|
90
|
+
base_url=base_url or self.base_url,
|
|
91
|
+
timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
|
|
92
|
+
max_retries=self.max_retries if max_retries is None else max_retries,
|
|
93
|
+
default_headers={**self._custom_headers, **(default_headers or {})},
|
|
94
|
+
http_client=self._http,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
def __enter__(self) -> Teleleo:
|
|
98
|
+
return self
|
|
99
|
+
|
|
100
|
+
def __exit__(
|
|
101
|
+
self,
|
|
102
|
+
exc_type: Optional[Type[BaseException]],
|
|
103
|
+
exc: Optional[BaseException],
|
|
104
|
+
tb: Optional[TracebackType],
|
|
105
|
+
) -> None:
|
|
106
|
+
self.close()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class AsyncTeleleo(AsyncResources, AsyncAPIClient):
|
|
110
|
+
"""Asynchronous client for the Teleleo API.
|
|
111
|
+
|
|
112
|
+
::
|
|
113
|
+
|
|
114
|
+
import asyncio
|
|
115
|
+
from teleleo import AsyncTeleleo
|
|
116
|
+
|
|
117
|
+
async def main() -> None:
|
|
118
|
+
async with AsyncTeleleo() as client:
|
|
119
|
+
page = await client.dongles.list()
|
|
120
|
+
async for dongle in page:
|
|
121
|
+
print(dongle.dongle_id, dongle.name)
|
|
122
|
+
|
|
123
|
+
asyncio.run(main())
|
|
124
|
+
|
|
125
|
+
Takes the same arguments as :class:`Teleleo`; ``http_client`` is an ``httpx.AsyncClient``.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
def __init__(
|
|
129
|
+
self,
|
|
130
|
+
*,
|
|
131
|
+
api_key: Optional[str] = None,
|
|
132
|
+
base_url: Union[str, httpx.URL, None] = None,
|
|
133
|
+
timeout: Union[Timeout, NotGiven] = NOT_GIVEN,
|
|
134
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
135
|
+
default_headers: Optional[Headers] = None,
|
|
136
|
+
http_client: Optional[httpx.AsyncClient] = None,
|
|
137
|
+
) -> None:
|
|
138
|
+
key, url, resolved_timeout = _resolve(api_key, base_url, timeout)
|
|
139
|
+
super().__init__(
|
|
140
|
+
api_key=key,
|
|
141
|
+
base_url=url,
|
|
142
|
+
timeout=resolved_timeout,
|
|
143
|
+
max_retries=max_retries,
|
|
144
|
+
default_headers=default_headers,
|
|
145
|
+
http_client=http_client,
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
def with_options(
|
|
149
|
+
self,
|
|
150
|
+
*,
|
|
151
|
+
api_key: Optional[str] = None,
|
|
152
|
+
base_url: Union[str, httpx.URL, None] = None,
|
|
153
|
+
timeout: Union[Timeout, NotGiven] = NOT_GIVEN,
|
|
154
|
+
max_retries: Optional[int] = None,
|
|
155
|
+
default_headers: Optional[Headers] = None,
|
|
156
|
+
) -> AsyncTeleleo:
|
|
157
|
+
"""A copy of the client with some options changed; it shares the connection pool with this one."""
|
|
158
|
+
return AsyncTeleleo(
|
|
159
|
+
api_key=api_key or self.api_key,
|
|
160
|
+
base_url=base_url or self.base_url,
|
|
161
|
+
timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
|
|
162
|
+
max_retries=self.max_retries if max_retries is None else max_retries,
|
|
163
|
+
default_headers={**self._custom_headers, **(default_headers or {})},
|
|
164
|
+
http_client=self._http,
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
async def __aenter__(self) -> AsyncTeleleo:
|
|
168
|
+
return self
|
|
169
|
+
|
|
170
|
+
async def __aexit__(
|
|
171
|
+
self,
|
|
172
|
+
exc_type: Optional[Type[BaseException]],
|
|
173
|
+
exc: Optional[BaseException],
|
|
174
|
+
tb: Optional[TracebackType],
|
|
175
|
+
) -> None:
|
|
176
|
+
await self.close()
|