leadveyor 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.
- leadveyor/__init__.py +59 -0
- leadveyor/_base_client.py +437 -0
- leadveyor/_client.py +237 -0
- leadveyor/_errors.py +160 -0
- leadveyor/_object.py +103 -0
- leadveyor/_pagination.py +146 -0
- leadveyor/_resource.py +18 -0
- leadveyor/_version.py +1 -0
- leadveyor/models.py +1052 -0
- leadveyor/py.typed +0 -0
- leadveyor/resources/__init__.py +21 -0
- leadveyor/resources/api_keys.py +128 -0
- leadveyor/resources/billing.py +178 -0
- leadveyor/resources/contacts.py +176 -0
- leadveyor/resources/crm.py +218 -0
- leadveyor/resources/destinations.py +334 -0
- leadveyor/resources/events.py +90 -0
- leadveyor/resources/facebook.py +154 -0
- leadveyor/resources/hubspot.py +218 -0
- leadveyor/resources/inbounds.py +186 -0
- leadveyor/resources/leads.py +212 -0
- leadveyor/resources/pipedrive.py +216 -0
- leadveyor/resources/places.py +90 -0
- leadveyor/resources/profiles.py +528 -0
- leadveyor/resources/reports.py +94 -0
- leadveyor/resources/sources.py +198 -0
- leadveyor/resources/templates.py +90 -0
- leadveyor/resources/usage.py +56 -0
- leadveyor/resources/workspaces.py +176 -0
- leadveyor/webhooks.py +139 -0
- leadveyor-0.1.0.dist-info/METADATA +227 -0
- leadveyor-0.1.0.dist-info/RECORD +34 -0
- leadveyor-0.1.0.dist-info/WHEEL +4 -0
- leadveyor-0.1.0.dist-info/licenses/LICENSE +21 -0
leadveyor/__init__.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Official Python client for the Leadveyor API. Docs: https://leadveyor.com/docs/sdk/python
|
|
2
|
+
|
|
3
|
+
.. code-block:: python
|
|
4
|
+
|
|
5
|
+
from leadveyor import Leadveyor
|
|
6
|
+
|
|
7
|
+
lv = Leadveyor() # reads LEADVEYOR_API_KEY
|
|
8
|
+
inbound = lv.inbounds.create(text="Hi, we need catering for 80 guests on 12 March", wait=True)
|
|
9
|
+
print(inbound.leads[0].evaluation.tier)
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from . import models
|
|
13
|
+
from ._base_client import DEFAULT_BASE_URL, NOT_GIVEN, NotGiven
|
|
14
|
+
from ._client import AsyncLeadveyor, Leadveyor
|
|
15
|
+
from ._errors import (
|
|
16
|
+
APIConnectionError,
|
|
17
|
+
APIError,
|
|
18
|
+
APITimeoutError,
|
|
19
|
+
AuthenticationError,
|
|
20
|
+
ConflictError,
|
|
21
|
+
InvalidRequestError,
|
|
22
|
+
LeadveyorError,
|
|
23
|
+
NotFoundError,
|
|
24
|
+
PermissionDeniedError,
|
|
25
|
+
QuotaExceededError,
|
|
26
|
+
RateLimitError,
|
|
27
|
+
SignatureVerificationError,
|
|
28
|
+
)
|
|
29
|
+
from ._object import LeadveyorObject
|
|
30
|
+
from ._pagination import AsyncPage, AsyncPageRequest, SyncPage
|
|
31
|
+
from ._version import __version__
|
|
32
|
+
from .webhooks import Webhook
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"Leadveyor",
|
|
36
|
+
"AsyncLeadveyor",
|
|
37
|
+
"Webhook",
|
|
38
|
+
"LeadveyorObject",
|
|
39
|
+
"SyncPage",
|
|
40
|
+
"AsyncPage",
|
|
41
|
+
"AsyncPageRequest",
|
|
42
|
+
"NOT_GIVEN",
|
|
43
|
+
"NotGiven",
|
|
44
|
+
"DEFAULT_BASE_URL",
|
|
45
|
+
"models",
|
|
46
|
+
"__version__",
|
|
47
|
+
"LeadveyorError",
|
|
48
|
+
"InvalidRequestError",
|
|
49
|
+
"AuthenticationError",
|
|
50
|
+
"PermissionDeniedError",
|
|
51
|
+
"NotFoundError",
|
|
52
|
+
"ConflictError",
|
|
53
|
+
"QuotaExceededError",
|
|
54
|
+
"RateLimitError",
|
|
55
|
+
"APIError",
|
|
56
|
+
"APIConnectionError",
|
|
57
|
+
"APITimeoutError",
|
|
58
|
+
"SignatureVerificationError",
|
|
59
|
+
]
|
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
"""Shared HTTP layer (retries, timeouts, error mapping). The generated clients add the resources on top."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import email.utils
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import platform
|
|
10
|
+
import random
|
|
11
|
+
import time
|
|
12
|
+
from typing import Any, Dict, Mapping, Optional, Type, TypeVar, Union, overload
|
|
13
|
+
from urllib.parse import quote
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from ._errors import APIConnectionError, APITimeoutError, AuthenticationError, LeadveyorError, error_from_response
|
|
18
|
+
from ._object import LeadveyorObject, convert
|
|
19
|
+
from ._pagination import AsyncPageRequest, SyncPage
|
|
20
|
+
from ._version import __version__
|
|
21
|
+
|
|
22
|
+
__all__ = ["NOT_GIVEN", "NotGiven", "DEFAULT_BASE_URL"]
|
|
23
|
+
|
|
24
|
+
DEFAULT_BASE_URL = "https://core.leadveyor.com"
|
|
25
|
+
DEFAULT_TIMEOUT = 60.0
|
|
26
|
+
DEFAULT_MAX_RETRIES = 2
|
|
27
|
+
|
|
28
|
+
#: Retried for requests that are safe to repeat.
|
|
29
|
+
_RETRY_STATUSES = {500, 502, 503, 504}
|
|
30
|
+
#: POST can create things twice if retried after the server got it; only 429 (rejected up front) is retried for POST.
|
|
31
|
+
_IDEMPOTENT_METHODS = {"GET", "PUT", "PATCH", "DELETE"}
|
|
32
|
+
|
|
33
|
+
T = TypeVar("T", bound=LeadveyorObject)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class NotGiven:
|
|
37
|
+
"""Marks an argument that was not passed (None is a real value: it sends JSON null)."""
|
|
38
|
+
|
|
39
|
+
_instance: Optional["NotGiven"] = None
|
|
40
|
+
|
|
41
|
+
def __new__(cls) -> "NotGiven":
|
|
42
|
+
if cls._instance is None:
|
|
43
|
+
cls._instance = super().__new__(cls)
|
|
44
|
+
return cls._instance
|
|
45
|
+
|
|
46
|
+
def __bool__(self) -> bool:
|
|
47
|
+
return False
|
|
48
|
+
|
|
49
|
+
def __repr__(self) -> str:
|
|
50
|
+
return "NOT_GIVEN"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
NOT_GIVEN = NotGiven()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _env(name: str) -> Optional[str]:
|
|
57
|
+
v = os.environ.get(name)
|
|
58
|
+
return v or None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def path_param(value: Union[str, int]) -> str:
|
|
62
|
+
"""Encodes a path parameter."""
|
|
63
|
+
return quote(str(value), safe="")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def build_query(query: Optional[Mapping[str, Any]]) -> Dict[str, str]:
|
|
67
|
+
"""Drops unset values; booleans as true / false."""
|
|
68
|
+
out: Dict[str, str] = {}
|
|
69
|
+
for k, v in (query or {}).items():
|
|
70
|
+
if v is None or isinstance(v, NotGiven):
|
|
71
|
+
continue
|
|
72
|
+
out[k] = ("true" if v else "false") if isinstance(v, bool) else str(v)
|
|
73
|
+
return out
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def build_body(fields: Mapping[str, Any]) -> Dict[str, Any]:
|
|
77
|
+
"""Drops arguments that were not passed."""
|
|
78
|
+
return {k: v for k, v in fields.items() if not isinstance(v, NotGiven)}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def retry_delay(attempt: int, retry_after: Optional[str]) -> float:
|
|
82
|
+
"""Exponential backoff with jitter (0.5 s, 1 s, 2 s … capped at 8 s); ``Retry-After`` wins when present."""
|
|
83
|
+
if retry_after:
|
|
84
|
+
try:
|
|
85
|
+
secs = float(retry_after)
|
|
86
|
+
if secs >= 0:
|
|
87
|
+
return min(secs, 60.0)
|
|
88
|
+
except ValueError:
|
|
89
|
+
try:
|
|
90
|
+
parsed = email.utils.parsedate_to_datetime(retry_after)
|
|
91
|
+
except (TypeError, ValueError):
|
|
92
|
+
parsed = None
|
|
93
|
+
if parsed is not None:
|
|
94
|
+
return min(max(parsed.timestamp() - time.time(), 0.0), 60.0)
|
|
95
|
+
base = min(0.5 * float(2**attempt), 8.0)
|
|
96
|
+
return base * (0.75 + random.random() * 0.5)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _parse(response: httpx.Response) -> Any:
|
|
100
|
+
text = response.text
|
|
101
|
+
if not text:
|
|
102
|
+
return None
|
|
103
|
+
ctype = response.headers.get("content-type", "")
|
|
104
|
+
if "json" in ctype or text.lstrip()[:1] in ("{", "["):
|
|
105
|
+
try:
|
|
106
|
+
return json.loads(text)
|
|
107
|
+
except ValueError:
|
|
108
|
+
return text
|
|
109
|
+
return text
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# Patched in tests.
|
|
113
|
+
_sleep = time.sleep
|
|
114
|
+
_async_sleep = asyncio.sleep
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class _ClientConfig:
|
|
118
|
+
def __init__(
|
|
119
|
+
self,
|
|
120
|
+
api_key: Optional[str],
|
|
121
|
+
*,
|
|
122
|
+
base_url: Optional[str],
|
|
123
|
+
workspace: Optional[str],
|
|
124
|
+
account: Optional[str],
|
|
125
|
+
timeout: Optional[float],
|
|
126
|
+
max_retries: Optional[int],
|
|
127
|
+
default_headers: Optional[Mapping[str, str]],
|
|
128
|
+
) -> None:
|
|
129
|
+
key = api_key or _env("LEADVEYOR_API_KEY")
|
|
130
|
+
if not key:
|
|
131
|
+
raise AuthenticationError(
|
|
132
|
+
'No API key. Pass it to Leadveyor("lv_live_…") or set LEADVEYOR_API_KEY. Keys: console → API keys.',
|
|
133
|
+
type="authentication_error",
|
|
134
|
+
)
|
|
135
|
+
self.api_key: str = key
|
|
136
|
+
self.base_url = (base_url or _env("LEADVEYOR_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
137
|
+
self.workspace = workspace
|
|
138
|
+
self.account = account
|
|
139
|
+
self.timeout = float(timeout) if timeout is not None else DEFAULT_TIMEOUT
|
|
140
|
+
self.max_retries = int(max_retries) if max_retries is not None else DEFAULT_MAX_RETRIES
|
|
141
|
+
self.default_headers = dict(default_headers or {})
|
|
142
|
+
|
|
143
|
+
def headers(self, workspace: Optional[str], account: Optional[str], extra: Optional[Mapping[str, str]], has_body: bool) -> Dict[str, str]:
|
|
144
|
+
h = {
|
|
145
|
+
"Accept": "application/json",
|
|
146
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
147
|
+
"User-Agent": f"leadveyor-sdk-python/{__version__} Python/{platform.python_version()}",
|
|
148
|
+
**self.default_headers,
|
|
149
|
+
}
|
|
150
|
+
ws = workspace or self.workspace
|
|
151
|
+
acc = account or self.account
|
|
152
|
+
if ws:
|
|
153
|
+
h["Leadveyor-Workspace"] = ws
|
|
154
|
+
if acc:
|
|
155
|
+
h["Leadveyor-Account"] = acc
|
|
156
|
+
if has_body:
|
|
157
|
+
h["Content-Type"] = "application/json"
|
|
158
|
+
h.update(extra or {})
|
|
159
|
+
return h
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _result(parsed: Any, cls: Optional[Type[LeadveyorObject]]) -> Any:
|
|
163
|
+
if parsed is None:
|
|
164
|
+
return None
|
|
165
|
+
if cls is not None and isinstance(parsed, dict):
|
|
166
|
+
return cls.construct_from(parsed)
|
|
167
|
+
return convert(parsed)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _transport_error(err: Exception, method: str, path: str, timeout: float) -> LeadveyorError:
|
|
171
|
+
if isinstance(err, httpx.TimeoutException):
|
|
172
|
+
e: LeadveyorError = APITimeoutError(f"Request timed out after {timeout:g} s: {method} {path}", type="connection_error")
|
|
173
|
+
else:
|
|
174
|
+
e = APIConnectionError(f"Could not reach the Leadveyor API ({method} {path}): {err}", type="connection_error")
|
|
175
|
+
e.__cause__ = err
|
|
176
|
+
return e
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class SyncAPIClient:
|
|
180
|
+
"""Synchronous HTTP layer of ``Leadveyor``."""
|
|
181
|
+
|
|
182
|
+
def __init__(
|
|
183
|
+
self,
|
|
184
|
+
api_key: Optional[str] = None,
|
|
185
|
+
*,
|
|
186
|
+
base_url: Optional[str] = None,
|
|
187
|
+
workspace: Optional[str] = None,
|
|
188
|
+
account: Optional[str] = None,
|
|
189
|
+
timeout: Optional[float] = None,
|
|
190
|
+
max_retries: Optional[int] = None,
|
|
191
|
+
default_headers: Optional[Mapping[str, str]] = None,
|
|
192
|
+
http_client: Optional[httpx.Client] = None,
|
|
193
|
+
) -> None:
|
|
194
|
+
self._config = _ClientConfig(
|
|
195
|
+
api_key, base_url=base_url, workspace=workspace, account=account, timeout=timeout, max_retries=max_retries, default_headers=default_headers
|
|
196
|
+
)
|
|
197
|
+
self._options: Dict[str, Any] = dict(
|
|
198
|
+
api_key=self._config.api_key, base_url=base_url, workspace=workspace, account=account, timeout=timeout,
|
|
199
|
+
max_retries=max_retries, default_headers=default_headers,
|
|
200
|
+
)
|
|
201
|
+
self._own_http = http_client is None
|
|
202
|
+
self._http = http_client or httpx.Client()
|
|
203
|
+
self._options["http_client"] = self._http
|
|
204
|
+
|
|
205
|
+
@property
|
|
206
|
+
def livemode(self) -> bool:
|
|
207
|
+
"""``lv_test_…`` keys work on test data only."""
|
|
208
|
+
return not self._config.api_key.startswith("lv_test_")
|
|
209
|
+
|
|
210
|
+
def close(self) -> None:
|
|
211
|
+
"""Closes the HTTP connection pool (only if the client created it)."""
|
|
212
|
+
if self._own_http:
|
|
213
|
+
self._http.close()
|
|
214
|
+
|
|
215
|
+
def __enter__(self: Any) -> Any:
|
|
216
|
+
return self
|
|
217
|
+
|
|
218
|
+
def __exit__(self, *args: Any) -> None:
|
|
219
|
+
self.close()
|
|
220
|
+
|
|
221
|
+
@overload
|
|
222
|
+
def _request(
|
|
223
|
+
self,
|
|
224
|
+
method: str,
|
|
225
|
+
path: str,
|
|
226
|
+
*,
|
|
227
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
228
|
+
body: Optional[Mapping[str, Any]] = None,
|
|
229
|
+
cls: Type[T],
|
|
230
|
+
idempotent: Optional[bool] = None,
|
|
231
|
+
workspace: Optional[str] = None,
|
|
232
|
+
account: Optional[str] = None,
|
|
233
|
+
timeout: Optional[float] = None,
|
|
234
|
+
max_retries: Optional[int] = None,
|
|
235
|
+
extra_headers: Optional[Mapping[str, str]] = None,
|
|
236
|
+
) -> T: ...
|
|
237
|
+
|
|
238
|
+
@overload
|
|
239
|
+
def _request(
|
|
240
|
+
self,
|
|
241
|
+
method: str,
|
|
242
|
+
path: str,
|
|
243
|
+
*,
|
|
244
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
245
|
+
body: Optional[Mapping[str, Any]] = None,
|
|
246
|
+
cls: None = None,
|
|
247
|
+
idempotent: Optional[bool] = None,
|
|
248
|
+
workspace: Optional[str] = None,
|
|
249
|
+
account: Optional[str] = None,
|
|
250
|
+
timeout: Optional[float] = None,
|
|
251
|
+
max_retries: Optional[int] = None,
|
|
252
|
+
extra_headers: Optional[Mapping[str, str]] = None,
|
|
253
|
+
) -> Any: ...
|
|
254
|
+
|
|
255
|
+
def _request(
|
|
256
|
+
self,
|
|
257
|
+
method: str,
|
|
258
|
+
path: str,
|
|
259
|
+
*,
|
|
260
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
261
|
+
body: Optional[Mapping[str, Any]] = None,
|
|
262
|
+
cls: Optional[Type[LeadveyorObject]] = None,
|
|
263
|
+
idempotent: Optional[bool] = None,
|
|
264
|
+
workspace: Optional[str] = None,
|
|
265
|
+
account: Optional[str] = None,
|
|
266
|
+
timeout: Optional[float] = None,
|
|
267
|
+
max_retries: Optional[int] = None,
|
|
268
|
+
extra_headers: Optional[Mapping[str, str]] = None,
|
|
269
|
+
) -> Any:
|
|
270
|
+
cfg = self._config
|
|
271
|
+
url = cfg.base_url + path
|
|
272
|
+
params = build_query(query)
|
|
273
|
+
content = json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode() if body is not None else None
|
|
274
|
+
headers = cfg.headers(workspace, account, extra_headers, content is not None)
|
|
275
|
+
retries = cfg.max_retries if max_retries is None else max_retries
|
|
276
|
+
t = cfg.timeout if timeout is None else float(timeout)
|
|
277
|
+
safe = (method in _IDEMPOTENT_METHODS) if idempotent is None else idempotent
|
|
278
|
+
attempt = 0
|
|
279
|
+
while True:
|
|
280
|
+
can_retry = attempt < retries
|
|
281
|
+
try:
|
|
282
|
+
res = self._http.request(method, url, params=params, content=content, headers=headers, timeout=t)
|
|
283
|
+
except httpx.TransportError as err:
|
|
284
|
+
if can_retry and safe:
|
|
285
|
+
_sleep(retry_delay(attempt, None))
|
|
286
|
+
attempt += 1
|
|
287
|
+
continue
|
|
288
|
+
raise _transport_error(err, method, path, t) from err
|
|
289
|
+
parsed = _parse(res)
|
|
290
|
+
if 200 <= res.status_code < 300:
|
|
291
|
+
return _result(parsed, cls)
|
|
292
|
+
if (res.status_code == 429 or (res.status_code in _RETRY_STATUSES and safe)) and can_retry:
|
|
293
|
+
_sleep(retry_delay(attempt, res.headers.get("retry-after")))
|
|
294
|
+
attempt += 1
|
|
295
|
+
continue
|
|
296
|
+
raise error_from_response(res.status_code, parsed, dict(res.headers))
|
|
297
|
+
|
|
298
|
+
def _request_page(self, path: str, query: Mapping[str, Any], item_cls: Type[T], **options: Any) -> SyncPage[T]:
|
|
299
|
+
def fetch(cursor: Optional[str]) -> LeadveyorObject:
|
|
300
|
+
q = dict(query, starting_after=cursor) if cursor is not None else dict(query)
|
|
301
|
+
res = self._request("GET", path, query=q, **options)
|
|
302
|
+
if not isinstance(res, LeadveyorObject):
|
|
303
|
+
raise LeadveyorError(f"Unexpected response for a list: {type(res).__name__}")
|
|
304
|
+
return res
|
|
305
|
+
|
|
306
|
+
start = query.get("starting_after")
|
|
307
|
+
return SyncPage(fetch(start if isinstance(start, str) else None), item_cls, fetch)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
class AsyncAPIClient:
|
|
311
|
+
"""Asynchronous HTTP layer of ``AsyncLeadveyor``."""
|
|
312
|
+
|
|
313
|
+
def __init__(
|
|
314
|
+
self,
|
|
315
|
+
api_key: Optional[str] = None,
|
|
316
|
+
*,
|
|
317
|
+
base_url: Optional[str] = None,
|
|
318
|
+
workspace: Optional[str] = None,
|
|
319
|
+
account: Optional[str] = None,
|
|
320
|
+
timeout: Optional[float] = None,
|
|
321
|
+
max_retries: Optional[int] = None,
|
|
322
|
+
default_headers: Optional[Mapping[str, str]] = None,
|
|
323
|
+
http_client: Optional[httpx.AsyncClient] = None,
|
|
324
|
+
) -> None:
|
|
325
|
+
self._config = _ClientConfig(
|
|
326
|
+
api_key, base_url=base_url, workspace=workspace, account=account, timeout=timeout, max_retries=max_retries, default_headers=default_headers
|
|
327
|
+
)
|
|
328
|
+
self._options: Dict[str, Any] = dict(
|
|
329
|
+
api_key=self._config.api_key, base_url=base_url, workspace=workspace, account=account, timeout=timeout,
|
|
330
|
+
max_retries=max_retries, default_headers=default_headers,
|
|
331
|
+
)
|
|
332
|
+
self._own_http = http_client is None
|
|
333
|
+
self._http = http_client or httpx.AsyncClient()
|
|
334
|
+
self._options["http_client"] = self._http
|
|
335
|
+
|
|
336
|
+
@property
|
|
337
|
+
def livemode(self) -> bool:
|
|
338
|
+
"""``lv_test_…`` keys work on test data only."""
|
|
339
|
+
return not self._config.api_key.startswith("lv_test_")
|
|
340
|
+
|
|
341
|
+
async def close(self) -> None:
|
|
342
|
+
if self._own_http:
|
|
343
|
+
await self._http.aclose()
|
|
344
|
+
|
|
345
|
+
async def __aenter__(self: Any) -> Any:
|
|
346
|
+
return self
|
|
347
|
+
|
|
348
|
+
async def __aexit__(self, *args: Any) -> None:
|
|
349
|
+
await self.close()
|
|
350
|
+
|
|
351
|
+
@overload
|
|
352
|
+
async def _request(
|
|
353
|
+
self,
|
|
354
|
+
method: str,
|
|
355
|
+
path: str,
|
|
356
|
+
*,
|
|
357
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
358
|
+
body: Optional[Mapping[str, Any]] = None,
|
|
359
|
+
cls: Type[T],
|
|
360
|
+
idempotent: Optional[bool] = None,
|
|
361
|
+
workspace: Optional[str] = None,
|
|
362
|
+
account: Optional[str] = None,
|
|
363
|
+
timeout: Optional[float] = None,
|
|
364
|
+
max_retries: Optional[int] = None,
|
|
365
|
+
extra_headers: Optional[Mapping[str, str]] = None,
|
|
366
|
+
) -> T: ...
|
|
367
|
+
|
|
368
|
+
@overload
|
|
369
|
+
async def _request(
|
|
370
|
+
self,
|
|
371
|
+
method: str,
|
|
372
|
+
path: str,
|
|
373
|
+
*,
|
|
374
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
375
|
+
body: Optional[Mapping[str, Any]] = None,
|
|
376
|
+
cls: None = None,
|
|
377
|
+
idempotent: Optional[bool] = None,
|
|
378
|
+
workspace: Optional[str] = None,
|
|
379
|
+
account: Optional[str] = None,
|
|
380
|
+
timeout: Optional[float] = None,
|
|
381
|
+
max_retries: Optional[int] = None,
|
|
382
|
+
extra_headers: Optional[Mapping[str, str]] = None,
|
|
383
|
+
) -> Any: ...
|
|
384
|
+
|
|
385
|
+
async def _request(
|
|
386
|
+
self,
|
|
387
|
+
method: str,
|
|
388
|
+
path: str,
|
|
389
|
+
*,
|
|
390
|
+
query: Optional[Mapping[str, Any]] = None,
|
|
391
|
+
body: Optional[Mapping[str, Any]] = None,
|
|
392
|
+
cls: Optional[Type[LeadveyorObject]] = None,
|
|
393
|
+
idempotent: Optional[bool] = None,
|
|
394
|
+
workspace: Optional[str] = None,
|
|
395
|
+
account: Optional[str] = None,
|
|
396
|
+
timeout: Optional[float] = None,
|
|
397
|
+
max_retries: Optional[int] = None,
|
|
398
|
+
extra_headers: Optional[Mapping[str, str]] = None,
|
|
399
|
+
) -> Any:
|
|
400
|
+
cfg = self._config
|
|
401
|
+
url = cfg.base_url + path
|
|
402
|
+
params = build_query(query)
|
|
403
|
+
content = json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode() if body is not None else None
|
|
404
|
+
headers = cfg.headers(workspace, account, extra_headers, content is not None)
|
|
405
|
+
retries = cfg.max_retries if max_retries is None else max_retries
|
|
406
|
+
t = cfg.timeout if timeout is None else float(timeout)
|
|
407
|
+
safe = (method in _IDEMPOTENT_METHODS) if idempotent is None else idempotent
|
|
408
|
+
attempt = 0
|
|
409
|
+
while True:
|
|
410
|
+
can_retry = attempt < retries
|
|
411
|
+
try:
|
|
412
|
+
res = await self._http.request(method, url, params=params, content=content, headers=headers, timeout=t)
|
|
413
|
+
except httpx.TransportError as err:
|
|
414
|
+
if can_retry and safe:
|
|
415
|
+
await _async_sleep(retry_delay(attempt, None))
|
|
416
|
+
attempt += 1
|
|
417
|
+
continue
|
|
418
|
+
raise _transport_error(err, method, path, t) from err
|
|
419
|
+
parsed = _parse(res)
|
|
420
|
+
if 200 <= res.status_code < 300:
|
|
421
|
+
return _result(parsed, cls)
|
|
422
|
+
if (res.status_code == 429 or (res.status_code in _RETRY_STATUSES and safe)) and can_retry:
|
|
423
|
+
await _async_sleep(retry_delay(attempt, res.headers.get("retry-after")))
|
|
424
|
+
attempt += 1
|
|
425
|
+
continue
|
|
426
|
+
raise error_from_response(res.status_code, parsed, dict(res.headers))
|
|
427
|
+
|
|
428
|
+
def _request_page(self, path: str, query: Mapping[str, Any], item_cls: Type[T], **options: Any) -> AsyncPageRequest[T]:
|
|
429
|
+
async def fetch(cursor: Optional[str]) -> LeadveyorObject:
|
|
430
|
+
q = dict(query, starting_after=cursor) if cursor is not None else dict(query)
|
|
431
|
+
res = await self._request("GET", path, query=q, **options)
|
|
432
|
+
if not isinstance(res, LeadveyorObject):
|
|
433
|
+
raise LeadveyorError(f"Unexpected response for a list: {type(res).__name__}")
|
|
434
|
+
return res
|
|
435
|
+
|
|
436
|
+
start = query.get("starting_after")
|
|
437
|
+
return AsyncPageRequest(item_cls, fetch, start if isinstance(start, str) else None)
|