pylekto 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.
- pylekto/__init__.py +41 -0
- pylekto/_http.py +354 -0
- pylekto/_lekto.py +3 -0
- pylekto/_sse.py +43 -0
- pylekto/client.py +155 -0
- pylekto/exceptions.py +124 -0
- pylekto/models.py +8244 -0
- pylekto/py.typed +0 -0
- pylekto/resources/__init__.py +59 -0
- pylekto/resources/_base.py +14 -0
- pylekto/resources/auth.py +19 -0
- pylekto/resources/documents.py +724 -0
- pylekto/resources/events.py +38 -0
- pylekto/resources/health.py +24 -0
- pylekto/resources/identifiers.py +60 -0
- pylekto/resources/inbox.py +125 -0
- pylekto/resources/lenses.py +96 -0
- pylekto/resources/mail.py +286 -0
- pylekto/resources/master_data.py +451 -0
- pylekto/resources/open_identifiers.py +171 -0
- pylekto/resources/operations.py +378 -0
- pylekto/resources/relations.py +62 -0
- pylekto/resources/rules.py +235 -0
- pylekto/resources/search.py +149 -0
- pylekto/resources/spaces.py +123 -0
- pylekto/resources/users.py +126 -0
- pylekto/resources/webhooks.py +226 -0
- pylekto/types.py +126 -0
- pylekto/webhooks.py +269 -0
- pylekto-0.1.0.dist-info/METADATA +102 -0
- pylekto-0.1.0.dist-info/RECORD +33 -0
- pylekto-0.1.0.dist-info/WHEEL +4 -0
- pylekto-0.1.0.dist-info/licenses/LICENSE +21 -0
pylekto/__init__.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Async Python client for the Lekto DMS REST API."""
|
|
2
|
+
|
|
3
|
+
from pylekto import webhooks
|
|
4
|
+
from pylekto._lekto import LEKTO_VERSION
|
|
5
|
+
from pylekto.client import LektoClient
|
|
6
|
+
from pylekto.exceptions import (
|
|
7
|
+
LektoApiError,
|
|
8
|
+
LektoAuthenticationError,
|
|
9
|
+
LektoConflictError,
|
|
10
|
+
LektoConnectionError,
|
|
11
|
+
LektoError,
|
|
12
|
+
LektoForbiddenError,
|
|
13
|
+
LektoNotFoundError,
|
|
14
|
+
LektoRateLimitError,
|
|
15
|
+
LektoResponseError,
|
|
16
|
+
LektoServerError,
|
|
17
|
+
LektoTimeoutError,
|
|
18
|
+
LektoValidationError,
|
|
19
|
+
LektoVersionWarning,
|
|
20
|
+
WebhookVerificationError,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"LEKTO_VERSION",
|
|
25
|
+
"LektoApiError",
|
|
26
|
+
"LektoAuthenticationError",
|
|
27
|
+
"LektoClient",
|
|
28
|
+
"LektoConflictError",
|
|
29
|
+
"LektoConnectionError",
|
|
30
|
+
"LektoError",
|
|
31
|
+
"LektoForbiddenError",
|
|
32
|
+
"LektoNotFoundError",
|
|
33
|
+
"LektoRateLimitError",
|
|
34
|
+
"LektoResponseError",
|
|
35
|
+
"LektoServerError",
|
|
36
|
+
"LektoTimeoutError",
|
|
37
|
+
"LektoValidationError",
|
|
38
|
+
"LektoVersionWarning",
|
|
39
|
+
"WebhookVerificationError",
|
|
40
|
+
"webhooks",
|
|
41
|
+
]
|
pylekto/_http.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
"""Requests to Lekto's REST API: the token, problem details as exceptions, pages of items."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Collection, Mapping, Sequence
|
|
5
|
+
from contextlib import asynccontextmanager
|
|
6
|
+
from datetime import date
|
|
7
|
+
from http import HTTPStatus
|
|
8
|
+
from typing import IO, Any, Protocol, TypedDict, Unpack
|
|
9
|
+
from uuid import UUID
|
|
10
|
+
|
|
11
|
+
import httpx2
|
|
12
|
+
from pydantic import BaseModel, SecretBytes, SecretStr, TypeAdapter, ValidationError
|
|
13
|
+
|
|
14
|
+
from pylekto.exceptions import (
|
|
15
|
+
LektoApiError,
|
|
16
|
+
LektoAuthenticationError,
|
|
17
|
+
LektoConflictError,
|
|
18
|
+
LektoConnectionError,
|
|
19
|
+
LektoForbiddenError,
|
|
20
|
+
LektoNotFoundError,
|
|
21
|
+
LektoRateLimitError,
|
|
22
|
+
LektoResponseError,
|
|
23
|
+
LektoServerError,
|
|
24
|
+
LektoTimeoutError,
|
|
25
|
+
LektoValidationError,
|
|
26
|
+
)
|
|
27
|
+
from pylekto.models import Problem
|
|
28
|
+
|
|
29
|
+
API_PATH = "/api/v1"
|
|
30
|
+
# Only for the clients pylekto makes itself; a client passed in keeps its own settings.
|
|
31
|
+
TIMEOUT = httpx2.Timeout(30.0, connect=10.0)
|
|
32
|
+
# A stream waits for its next line as long as it takes; connecting has its usual limit.
|
|
33
|
+
STREAM = httpx2.Timeout(None, connect=10.0)
|
|
34
|
+
# Writes ids, dates and the like as JSON (for request bodies).
|
|
35
|
+
_JSON: TypeAdapter[Any] = TypeAdapter(Any)
|
|
36
|
+
# Lekto recognises a file by its content, not by the type a client names.
|
|
37
|
+
FILE_TYPE = "application/octet-stream"
|
|
38
|
+
|
|
39
|
+
type Params = Mapping[str, str | Sequence[str]]
|
|
40
|
+
type Upload = bytes | IO[bytes]
|
|
41
|
+
# A multipart part: a file (name, content, type) or a form field (None, its text).
|
|
42
|
+
type Part = tuple[str, Upload, str] | tuple[None, str]
|
|
43
|
+
type Files = Sequence[tuple[str, Part]]
|
|
44
|
+
|
|
45
|
+
_ERRORS: dict[int, type[LektoApiError]] = {
|
|
46
|
+
HTTPStatus.UNAUTHORIZED: LektoAuthenticationError,
|
|
47
|
+
HTTPStatus.FORBIDDEN: LektoForbiddenError,
|
|
48
|
+
HTTPStatus.NOT_FOUND: LektoNotFoundError,
|
|
49
|
+
HTTPStatus.CONFLICT: LektoConflictError,
|
|
50
|
+
HTTPStatus.UNPROCESSABLE_ENTITY: LektoValidationError,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Send(TypedDict, total=False):
|
|
55
|
+
"""What a request carries besides method and path.
|
|
56
|
+
|
|
57
|
+
``files`` makes a ``multipart/form-data`` body; form fields go in it as ``(None, text)``,
|
|
58
|
+
because Lekto reads them only there.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
params: Params
|
|
62
|
+
json: Any
|
|
63
|
+
files: Files
|
|
64
|
+
accept: Collection[int]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class Http:
|
|
68
|
+
"""Sends requests to one Lekto instance with its API token.
|
|
69
|
+
|
|
70
|
+
The httpx2 client may be shared with the rest of an application: the base URL and the token go
|
|
71
|
+
with each request, the client's own settings stay as they are.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
def __init__(self, url: str, token: str, client: httpx2.AsyncClient) -> None:
|
|
75
|
+
"""Remember where the API lies, the token and the client that sends the requests."""
|
|
76
|
+
self._api = url.rstrip("/") + API_PATH
|
|
77
|
+
self._headers = {"Authorization": f"Bearer {token}"}
|
|
78
|
+
self._client = client
|
|
79
|
+
|
|
80
|
+
async def request(self, method: str, path: str, **send: Unpack[Send]) -> httpx2.Response:
|
|
81
|
+
"""Send a request below ``/api/v1``; an error status raises, unless it is in ``accept``."""
|
|
82
|
+
return await exchange(self._client, method, self._api + path, self._headers, **send)
|
|
83
|
+
|
|
84
|
+
async def get[M: BaseModel](self, path: str, model: type[M], **send: Unpack[Send]) -> M:
|
|
85
|
+
"""GET a JSON answer as a model."""
|
|
86
|
+
return parse(await self.request("GET", path, **send), model)
|
|
87
|
+
|
|
88
|
+
async def call[M: BaseModel](
|
|
89
|
+
self, method: str, path: str, model: type[M], **send: Unpack[Send]
|
|
90
|
+
) -> M:
|
|
91
|
+
"""Send a request and read its JSON answer as a model."""
|
|
92
|
+
return parse(await self.request(method, path, **send), model)
|
|
93
|
+
|
|
94
|
+
async def call_as[T](
|
|
95
|
+
self, method: str, path: str, answer: TypeAdapter[T], **send: Unpack[Send]
|
|
96
|
+
) -> T:
|
|
97
|
+
"""Send a request and read its JSON answer as a type that is no model: a list, a union."""
|
|
98
|
+
return parse_as(await self.request(method, path, **send), answer)
|
|
99
|
+
|
|
100
|
+
async def call_empty(self, method: str, path: str, **send: Unpack[Send]) -> None:
|
|
101
|
+
"""Send a request whose answer has no body (204, or 202 without one)."""
|
|
102
|
+
await self.request(method, path, **send)
|
|
103
|
+
|
|
104
|
+
async def download(self, path: str, **send: Unpack[Send]) -> bytes:
|
|
105
|
+
"""GET the bytes of a file."""
|
|
106
|
+
return (await self.request("GET", path, **send)).content
|
|
107
|
+
|
|
108
|
+
async def lines(self, path: str, *, params: Params | None = None) -> AsyncIterator[str]:
|
|
109
|
+
"""GET a stream and yield its lines as they come, until Lekto ends it.
|
|
110
|
+
|
|
111
|
+
The stream may stay quiet for long: it waits for each line without a time limit.
|
|
112
|
+
"""
|
|
113
|
+
try:
|
|
114
|
+
async with self._client.stream(
|
|
115
|
+
"GET", self._api + path, params=params, headers=self._headers, timeout=STREAM
|
|
116
|
+
) as response:
|
|
117
|
+
if response.is_error:
|
|
118
|
+
await response.aread()
|
|
119
|
+
raise api_error(response)
|
|
120
|
+
async for line in response.aiter_lines():
|
|
121
|
+
yield line
|
|
122
|
+
except httpx2.TimeoutException as error:
|
|
123
|
+
message = f"Lekto did not answer GET {path} in time"
|
|
124
|
+
raise LektoTimeoutError(message) from error
|
|
125
|
+
except httpx2.TransportError as error:
|
|
126
|
+
message = f"Lekto is not reachable: {type(error).__name__}"
|
|
127
|
+
raise LektoConnectionError(message) from error
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
async def exchange(
|
|
131
|
+
client: httpx2.AsyncClient,
|
|
132
|
+
method: str,
|
|
133
|
+
url: str,
|
|
134
|
+
headers: Mapping[str, str],
|
|
135
|
+
**send: Unpack[Send],
|
|
136
|
+
) -> httpx2.Response:
|
|
137
|
+
"""Send a request to Lekto; a failed connection or an error status raises a LektoError."""
|
|
138
|
+
try:
|
|
139
|
+
response = await client.request(
|
|
140
|
+
method,
|
|
141
|
+
url,
|
|
142
|
+
params=send.get("params"),
|
|
143
|
+
json=send.get("json"),
|
|
144
|
+
files=send.get("files"),
|
|
145
|
+
headers=headers,
|
|
146
|
+
)
|
|
147
|
+
except httpx2.TimeoutException as error:
|
|
148
|
+
message = f"Lekto did not answer {method} {httpx2.URL(url).path} in time"
|
|
149
|
+
raise LektoTimeoutError(message) from error
|
|
150
|
+
except httpx2.TransportError as error:
|
|
151
|
+
message = f"Lekto is not reachable: {type(error).__name__}"
|
|
152
|
+
raise LektoConnectionError(message) from error
|
|
153
|
+
if response.is_error and response.status_code not in send.get("accept", ()):
|
|
154
|
+
raise api_error(response)
|
|
155
|
+
return response
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@asynccontextmanager
|
|
159
|
+
async def http_client(client: httpx2.AsyncClient | None) -> AsyncIterator[httpx2.AsyncClient]:
|
|
160
|
+
"""Yield the client given, or one made for the moment and closed afterwards."""
|
|
161
|
+
if client is not None:
|
|
162
|
+
yield client
|
|
163
|
+
return
|
|
164
|
+
own = httpx2.AsyncClient(timeout=TIMEOUT)
|
|
165
|
+
try:
|
|
166
|
+
yield own
|
|
167
|
+
finally:
|
|
168
|
+
await own.aclose()
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def query(**values: object) -> dict[str, str | list[str]]:
|
|
172
|
+
"""Turn query values into what Lekto reads: ids, dates and flags as text; None is left out."""
|
|
173
|
+
params: dict[str, str | list[str]] = {}
|
|
174
|
+
for name, value in values.items():
|
|
175
|
+
if value is None:
|
|
176
|
+
continue
|
|
177
|
+
if isinstance(value, Sequence) and not isinstance(value, str):
|
|
178
|
+
params[name] = [_text(item) for item in value]
|
|
179
|
+
else:
|
|
180
|
+
params[name] = _text(value)
|
|
181
|
+
return params
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _text(value: object) -> str:
|
|
185
|
+
"""Write one query value as Lekto reads it."""
|
|
186
|
+
if isinstance(value, bool):
|
|
187
|
+
return "true" if value else "false"
|
|
188
|
+
if isinstance(value, date):
|
|
189
|
+
return value.isoformat()
|
|
190
|
+
if isinstance(value, UUID | str | int | float):
|
|
191
|
+
return str(value)
|
|
192
|
+
message = f"no query value: {value!r}"
|
|
193
|
+
raise TypeError(message)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def body(model: BaseModel) -> Any:
|
|
197
|
+
"""Return the JSON of a request body: only the values set, so a change sends no others.
|
|
198
|
+
|
|
199
|
+
Secrets (a mailbox's password) go as they are: pydantic would write them as ``**********``.
|
|
200
|
+
"""
|
|
201
|
+
values = model.model_dump(mode="python", by_alias=True, exclude_unset=True)
|
|
202
|
+
return _JSON.dump_python(_reveal(values), mode="json")
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _reveal(value: object) -> object:
|
|
206
|
+
"""Put the values of the secrets in a dumped model in place of the secrets."""
|
|
207
|
+
if isinstance(value, SecretStr | SecretBytes):
|
|
208
|
+
return value.get_secret_value()
|
|
209
|
+
if isinstance(value, dict):
|
|
210
|
+
return {key: _reveal(item) for key, item in value.items()}
|
|
211
|
+
if isinstance(value, list):
|
|
212
|
+
return [_reveal(item) for item in value]
|
|
213
|
+
return value
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def parse[M: BaseModel](response: httpx2.Response, model: type[M]) -> M:
|
|
217
|
+
"""Read a JSON answer as a model; one that does not fit raises :class:`LektoResponseError`."""
|
|
218
|
+
try:
|
|
219
|
+
return model.model_validate_json(response.content)
|
|
220
|
+
except ValidationError as error:
|
|
221
|
+
request = response.request
|
|
222
|
+
message = f"Lekto's answer to {request.method} {request.url.path} is no {model.__name__}"
|
|
223
|
+
raise LektoResponseError(message) from error
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def parse_as[T](response: httpx2.Response, answer: TypeAdapter[T]) -> T:
|
|
227
|
+
"""Read a JSON answer as a type; one that does not fit raises :class:`LektoResponseError`."""
|
|
228
|
+
try:
|
|
229
|
+
return answer.validate_json(response.content)
|
|
230
|
+
except ValidationError as error:
|
|
231
|
+
request = response.request
|
|
232
|
+
message = f"Lekto's answer to {request.method} {request.url.path} does not fit"
|
|
233
|
+
raise LektoResponseError(message) from error
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def api_error(response: httpx2.Response) -> LektoApiError:
|
|
237
|
+
"""Build the exception for an error status, with the problem details of the answer."""
|
|
238
|
+
problem = _problem(response)
|
|
239
|
+
status = response.status_code
|
|
240
|
+
if status == HTTPStatus.TOO_MANY_REQUESTS:
|
|
241
|
+
return LektoRateLimitError(problem, _retry_after(response.headers.get("Retry-After")))
|
|
242
|
+
if status >= HTTPStatus.INTERNAL_SERVER_ERROR:
|
|
243
|
+
return LektoServerError(problem)
|
|
244
|
+
return _ERRORS.get(status, LektoApiError)(problem)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _problem(response: httpx2.Response) -> Problem:
|
|
248
|
+
"""Read the problem details; a body that holds none (a proxy's page) gives the status alone."""
|
|
249
|
+
try:
|
|
250
|
+
return Problem.model_validate_json(response.content)
|
|
251
|
+
except ValidationError:
|
|
252
|
+
pass
|
|
253
|
+
# A newer Lekto may send a reason code the models do not know: keep what reads plainly.
|
|
254
|
+
title = response.reason_phrase or "Error"
|
|
255
|
+
detail = None
|
|
256
|
+
try:
|
|
257
|
+
body = json.loads(response.content)
|
|
258
|
+
except ValueError:
|
|
259
|
+
body = None
|
|
260
|
+
if isinstance(body, dict):
|
|
261
|
+
title = body["title"] if isinstance(body.get("title"), str) else title
|
|
262
|
+
detail = body["detail"] if isinstance(body.get("detail"), str) else None
|
|
263
|
+
return Problem(title=title, status=response.status_code, detail=detail)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _retry_after(header: str | None) -> float | None:
|
|
267
|
+
"""Seconds from a ``Retry-After`` header that holds a number."""
|
|
268
|
+
try:
|
|
269
|
+
return max(float(header), 0.0) if header is not None else None
|
|
270
|
+
except ValueError:
|
|
271
|
+
return None
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
class CursorPage[T](Protocol):
|
|
275
|
+
"""A page of a list that continues with a cursor (documents, the inbox)."""
|
|
276
|
+
|
|
277
|
+
@property
|
|
278
|
+
def items(self) -> Sequence[T]:
|
|
279
|
+
"""The items of this page."""
|
|
280
|
+
...
|
|
281
|
+
|
|
282
|
+
@property
|
|
283
|
+
def next_cursor(self) -> str | None:
|
|
284
|
+
"""Where the next page starts; None on the last."""
|
|
285
|
+
...
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class OffsetPage[T](Protocol):
|
|
289
|
+
"""A page of a list that continues at an offset (jobs, deliveries, mails)."""
|
|
290
|
+
|
|
291
|
+
@property
|
|
292
|
+
def items(self) -> Sequence[T]:
|
|
293
|
+
"""The items of this page."""
|
|
294
|
+
...
|
|
295
|
+
|
|
296
|
+
@property
|
|
297
|
+
def next_offset(self) -> int | None:
|
|
298
|
+
"""Where the next page starts; None on the last."""
|
|
299
|
+
...
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
class TotalPage[T](Protocol):
|
|
303
|
+
"""A page of a list that says how many items it holds in all (open identifiers)."""
|
|
304
|
+
|
|
305
|
+
@property
|
|
306
|
+
def items(self) -> Sequence[T]:
|
|
307
|
+
"""The items of this page."""
|
|
308
|
+
...
|
|
309
|
+
|
|
310
|
+
@property
|
|
311
|
+
def total(self) -> int:
|
|
312
|
+
"""How many items the list holds in all."""
|
|
313
|
+
...
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
async def cursor_items[T](
|
|
317
|
+
fetch: Callable[[str | None], Awaitable[CursorPage[T]]],
|
|
318
|
+
) -> AsyncIterator[T]:
|
|
319
|
+
"""Every item of a list, page after page; ``fetch`` gets the cursor (None for the first)."""
|
|
320
|
+
cursor: str | None = None
|
|
321
|
+
while True:
|
|
322
|
+
page = await fetch(cursor)
|
|
323
|
+
for item in page.items:
|
|
324
|
+
yield item
|
|
325
|
+
if page.next_cursor is None:
|
|
326
|
+
return
|
|
327
|
+
cursor = page.next_cursor
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
async def offset_items[T](fetch: Callable[[int], Awaitable[OffsetPage[T]]]) -> AsyncIterator[T]:
|
|
331
|
+
"""Every item of a list, page after page; ``fetch`` gets the offset (0 for the first)."""
|
|
332
|
+
offset = 0
|
|
333
|
+
while True:
|
|
334
|
+
page = await fetch(offset)
|
|
335
|
+
for item in page.items:
|
|
336
|
+
yield item
|
|
337
|
+
if page.next_offset is None:
|
|
338
|
+
return
|
|
339
|
+
offset = page.next_offset
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
async def total_items[T](fetch: Callable[[int], Awaitable[TotalPage[T]]]) -> AsyncIterator[T]:
|
|
343
|
+
"""Every item of a list that gives its total instead of the next offset (open identifiers).
|
|
344
|
+
|
|
345
|
+
An empty page ends it too: the total may shrink while the pages are read.
|
|
346
|
+
"""
|
|
347
|
+
offset = 0
|
|
348
|
+
while True:
|
|
349
|
+
page = await fetch(offset)
|
|
350
|
+
for item in page.items:
|
|
351
|
+
yield item
|
|
352
|
+
offset += len(page.items)
|
|
353
|
+
if not page.items or offset >= page.total:
|
|
354
|
+
return
|
pylekto/_lekto.py
ADDED
pylekto/_sse.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Server-sent events: the lines of a ``text/event-stream`` as events."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from collections.abc import AsyncIterable, AsyncIterator
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class ServerSentEvent:
|
|
12
|
+
"""One event of a stream: its type, its data and the id the server gave it."""
|
|
13
|
+
|
|
14
|
+
event: str
|
|
15
|
+
data: str
|
|
16
|
+
id: str | None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def server_sent_events(lines: AsyncIterable[str]) -> AsyncIterator[ServerSentEvent]:
|
|
20
|
+
"""Yield the events the lines of a stream make, as the HTML standard reads them.
|
|
21
|
+
|
|
22
|
+
A blank line ends an event; lines that start with ``:`` are comments; several ``data`` lines
|
|
23
|
+
join with line breaks; an event without data is no event.
|
|
24
|
+
"""
|
|
25
|
+
event, last_id = "", None
|
|
26
|
+
data: list[str] = []
|
|
27
|
+
async for raw in lines:
|
|
28
|
+
line = raw.rstrip("\r\n")
|
|
29
|
+
if not line:
|
|
30
|
+
if data:
|
|
31
|
+
yield ServerSentEvent(event or "message", "\n".join(data), last_id)
|
|
32
|
+
event, data = "", []
|
|
33
|
+
continue
|
|
34
|
+
if line.startswith(":"):
|
|
35
|
+
continue
|
|
36
|
+
name, _, value = line.partition(":")
|
|
37
|
+
value = value.removeprefix(" ")
|
|
38
|
+
if name == "event":
|
|
39
|
+
event = value
|
|
40
|
+
elif name == "data":
|
|
41
|
+
data.append(value)
|
|
42
|
+
elif name == "id" and "\0" not in value:
|
|
43
|
+
last_id = value
|
pylekto/client.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""The client of one Lekto instance."""
|
|
2
|
+
|
|
3
|
+
import warnings
|
|
4
|
+
from typing import TYPE_CHECKING, Self
|
|
5
|
+
|
|
6
|
+
import httpx2
|
|
7
|
+
|
|
8
|
+
from pylekto._http import TIMEOUT, Http
|
|
9
|
+
from pylekto._lekto import LEKTO_VERSION
|
|
10
|
+
from pylekto.exceptions import LektoVersionWarning
|
|
11
|
+
from pylekto.resources import (
|
|
12
|
+
AuthResource,
|
|
13
|
+
AutomationResource,
|
|
14
|
+
ClassifierResource,
|
|
15
|
+
ContactsResource,
|
|
16
|
+
DocumentsResource,
|
|
17
|
+
DocumentTypesResource,
|
|
18
|
+
EventsResource,
|
|
19
|
+
ExpectedResource,
|
|
20
|
+
FieldsResource,
|
|
21
|
+
HealthResource,
|
|
22
|
+
IdentifiersResource,
|
|
23
|
+
InboxResource,
|
|
24
|
+
JobsResource,
|
|
25
|
+
LensesResource,
|
|
26
|
+
MailboxesResource,
|
|
27
|
+
MailRulesResource,
|
|
28
|
+
OpenIdentifiersResource,
|
|
29
|
+
PipelineResource,
|
|
30
|
+
PushResource,
|
|
31
|
+
RelationsResource,
|
|
32
|
+
RulesResource,
|
|
33
|
+
SearchResource,
|
|
34
|
+
SpacesResource,
|
|
35
|
+
TagsResource,
|
|
36
|
+
UsersResource,
|
|
37
|
+
WebhooksResource,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
if TYPE_CHECKING:
|
|
41
|
+
from types import TracebackType
|
|
42
|
+
|
|
43
|
+
from pylekto.models import Me
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class LektoClient:
|
|
47
|
+
"""The client of one Lekto instance, authenticated with an API token.
|
|
48
|
+
|
|
49
|
+
pylekto sends requests and reads the answers; it repeats nothing. An error raises a
|
|
50
|
+
:class:`pylekto.LektoError`, and whether to try again is up to the caller.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
url: The address of the instance, such as ``https://lekto.example.com``.
|
|
54
|
+
token: A personal API token (``lekto_…``); its scope decides what the client may do.
|
|
55
|
+
client: An httpx2 client to send the requests with, such as one the application shares.
|
|
56
|
+
pylekto never closes it. Without one, pylekto makes its own and closes it in
|
|
57
|
+
:meth:`close`.
|
|
58
|
+
|
|
59
|
+
Example::
|
|
60
|
+
|
|
61
|
+
async with LektoClient("https://lekto.example.com", "lekto_…") as lekto:
|
|
62
|
+
me = await lekto.auth.me()
|
|
63
|
+
print(me.user.username)
|
|
64
|
+
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
def __init__(self, url: str, token: str, *, client: httpx2.AsyncClient | None = None) -> None:
|
|
68
|
+
"""Prepare the client; nothing is sent before the first request."""
|
|
69
|
+
self._own_client = client is None
|
|
70
|
+
self._client = httpx2.AsyncClient(timeout=TIMEOUT) if client is None else client
|
|
71
|
+
http = Http(url, token, self._client)
|
|
72
|
+
self.auth = AuthResource(http)
|
|
73
|
+
self.automation = AutomationResource(http)
|
|
74
|
+
self.classifier = ClassifierResource(http)
|
|
75
|
+
self.contacts = ContactsResource(http)
|
|
76
|
+
self.document_types = DocumentTypesResource(http)
|
|
77
|
+
self.documents = DocumentsResource(http)
|
|
78
|
+
self.events = EventsResource(http)
|
|
79
|
+
self.expected = ExpectedResource(http)
|
|
80
|
+
self.fields = FieldsResource(http)
|
|
81
|
+
self.health = HealthResource(http)
|
|
82
|
+
self.identifiers = IdentifiersResource(http)
|
|
83
|
+
self.inbox = InboxResource(http)
|
|
84
|
+
self.jobs = JobsResource(http)
|
|
85
|
+
self.lenses = LensesResource(http)
|
|
86
|
+
self.mail_rules = MailRulesResource(http)
|
|
87
|
+
self.mailboxes = MailboxesResource(http)
|
|
88
|
+
self.open_identifiers = OpenIdentifiersResource(http)
|
|
89
|
+
self.pipeline = PipelineResource(http)
|
|
90
|
+
self.push = PushResource(http)
|
|
91
|
+
self.relations = RelationsResource(http)
|
|
92
|
+
self.rules = RulesResource(http)
|
|
93
|
+
self.search = SearchResource(http)
|
|
94
|
+
self.spaces = SpacesResource(http)
|
|
95
|
+
self.tags = TagsResource(http)
|
|
96
|
+
self.users = UsersResource(http)
|
|
97
|
+
self.webhooks = WebhooksResource(http)
|
|
98
|
+
self.lekto_version: str | None = None
|
|
99
|
+
|
|
100
|
+
async def __aenter__(self) -> Self:
|
|
101
|
+
"""Connect (:meth:`connect`); a failure closes the client again."""
|
|
102
|
+
try:
|
|
103
|
+
await self.connect()
|
|
104
|
+
except BaseException:
|
|
105
|
+
await self.close()
|
|
106
|
+
raise
|
|
107
|
+
return self
|
|
108
|
+
|
|
109
|
+
async def __aexit__(
|
|
110
|
+
self,
|
|
111
|
+
exc_type: type[BaseException] | None,
|
|
112
|
+
exc_value: BaseException | None,
|
|
113
|
+
traceback: TracebackType | None,
|
|
114
|
+
) -> None:
|
|
115
|
+
"""Close the client (:meth:`close`)."""
|
|
116
|
+
await self.close()
|
|
117
|
+
|
|
118
|
+
async def connect(self) -> Me:
|
|
119
|
+
"""Ask who calls and compare Lekto's version with the one whose API pylekto speaks.
|
|
120
|
+
|
|
121
|
+
Another version gives a :class:`pylekto.LektoVersionWarning`: while Lekto is in beta,
|
|
122
|
+
each release may change its API.
|
|
123
|
+
|
|
124
|
+
Example::
|
|
125
|
+
|
|
126
|
+
lekto = LektoClient("https://lekto.example.com", "lekto_…")
|
|
127
|
+
me = await lekto.connect()
|
|
128
|
+
print(lekto.lekto_version)
|
|
129
|
+
|
|
130
|
+
"""
|
|
131
|
+
me = await self.auth.me()
|
|
132
|
+
self.lekto_version = me.lekto_version
|
|
133
|
+
if me.lekto_version != LEKTO_VERSION:
|
|
134
|
+
warnings.warn(
|
|
135
|
+
f"Lekto {me.lekto_version} answers; this pylekto speaks the API of Lekto "
|
|
136
|
+
f"{LEKTO_VERSION}",
|
|
137
|
+
LektoVersionWarning,
|
|
138
|
+
stacklevel=2,
|
|
139
|
+
)
|
|
140
|
+
return me
|
|
141
|
+
|
|
142
|
+
async def close(self) -> None:
|
|
143
|
+
"""Close the httpx2 client pylekto made; one passed in stays open.
|
|
144
|
+
|
|
145
|
+
Example::
|
|
146
|
+
|
|
147
|
+
lekto = LektoClient("https://lekto.example.com", "lekto_…")
|
|
148
|
+
try:
|
|
149
|
+
health = await lekto.health.get()
|
|
150
|
+
finally:
|
|
151
|
+
await lekto.close()
|
|
152
|
+
|
|
153
|
+
"""
|
|
154
|
+
if self._own_client:
|
|
155
|
+
await self._client.aclose()
|