frappex-client 0.1.1__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.
- frappex_client/__init__.py +60 -0
- frappex_client/_async_client.py +442 -0
- frappex_client/_auth.py +116 -0
- frappex_client/_base.py +162 -0
- frappex_client/_client.py +437 -0
- frappex_client/_config.py +147 -0
- frappex_client/_operations.py +251 -0
- frappex_client/_protocol.py +248 -0
- frappex_client/exceptions.py +138 -0
- frappex_client/py.typed +0 -0
- frappex_client/types.py +17 -0
- frappex_client-0.1.1.dist-info/METADATA +382 -0
- frappex_client-0.1.1.dist-info/RECORD +15 -0
- frappex_client-0.1.1.dist-info/WHEEL +4 -0
- frappex_client-0.1.1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""frappex-client: a typed sync and async REST client for Frappe and ERPNext sites.
|
|
2
|
+
|
|
3
|
+
Quick start::
|
|
4
|
+
|
|
5
|
+
from frappex_client import Client, TokenAuth
|
|
6
|
+
|
|
7
|
+
with Client("https://erp.example.com", TokenAuth(api_key, api_secret)) as client:
|
|
8
|
+
open_todos = client.get_list("ToDo", filters={"status": "Open"})
|
|
9
|
+
|
|
10
|
+
:class:`AsyncClient` offers the same methods for ``asyncio`` programs.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from ._async_client import AsyncClient
|
|
14
|
+
from ._auth import Auth, BearerAuth, PasswordAuth, Secret, TokenAuth
|
|
15
|
+
from ._client import Client
|
|
16
|
+
from ._config import RetryPolicy
|
|
17
|
+
from .exceptions import (
|
|
18
|
+
APIError,
|
|
19
|
+
AuthenticationError,
|
|
20
|
+
ConfigurationError,
|
|
21
|
+
ConflictError,
|
|
22
|
+
FrappexError,
|
|
23
|
+
NotFoundError,
|
|
24
|
+
PermissionDeniedError,
|
|
25
|
+
RateLimitError,
|
|
26
|
+
RequestTimeoutError,
|
|
27
|
+
ResponseTooLargeError,
|
|
28
|
+
ServerError,
|
|
29
|
+
TransportError,
|
|
30
|
+
UnexpectedResponseError,
|
|
31
|
+
ValidationError,
|
|
32
|
+
)
|
|
33
|
+
from .types import Document, Filters
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"APIError",
|
|
37
|
+
"AsyncClient",
|
|
38
|
+
"Auth",
|
|
39
|
+
"AuthenticationError",
|
|
40
|
+
"BearerAuth",
|
|
41
|
+
"Client",
|
|
42
|
+
"ConfigurationError",
|
|
43
|
+
"ConflictError",
|
|
44
|
+
"Document",
|
|
45
|
+
"Filters",
|
|
46
|
+
"FrappexError",
|
|
47
|
+
"NotFoundError",
|
|
48
|
+
"PasswordAuth",
|
|
49
|
+
"PermissionDeniedError",
|
|
50
|
+
"RateLimitError",
|
|
51
|
+
"RequestTimeoutError",
|
|
52
|
+
"ResponseTooLargeError",
|
|
53
|
+
"RetryPolicy",
|
|
54
|
+
"Secret",
|
|
55
|
+
"ServerError",
|
|
56
|
+
"TokenAuth",
|
|
57
|
+
"TransportError",
|
|
58
|
+
"UnexpectedResponseError",
|
|
59
|
+
"ValidationError",
|
|
60
|
+
]
|
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
"""The asyncio client."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import io
|
|
7
|
+
import os
|
|
8
|
+
import ssl
|
|
9
|
+
from collections.abc import AsyncIterator, Mapping, Sequence
|
|
10
|
+
from types import TracebackType
|
|
11
|
+
from typing import Any, BinaryIO, Literal, TypeVar
|
|
12
|
+
|
|
13
|
+
import httpx
|
|
14
|
+
|
|
15
|
+
from . import _operations as ops
|
|
16
|
+
from ._auth import Auth, PasswordAuth
|
|
17
|
+
from ._base import (
|
|
18
|
+
CHUNK_SIZE,
|
|
19
|
+
DEFAULT_MAX_RESPONSE_BYTES,
|
|
20
|
+
DEFAULT_TIMEOUT,
|
|
21
|
+
ClientCore,
|
|
22
|
+
ResponseSize,
|
|
23
|
+
logger,
|
|
24
|
+
)
|
|
25
|
+
from ._config import RetryPolicy
|
|
26
|
+
from ._protocol import RawResponse, Request, decode, file_path, parse_retry_after
|
|
27
|
+
from .exceptions import FrappexError, TransportError, UnexpectedResponseError
|
|
28
|
+
from .types import Document, Filters
|
|
29
|
+
|
|
30
|
+
T = TypeVar("T")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AsyncClient(ClientCore):
|
|
34
|
+
"""Asyncio client for one Frappe site.
|
|
35
|
+
|
|
36
|
+
It has the same methods as :class:`~frappex_client.Client`, awaited. Use it as an
|
|
37
|
+
async context manager so connections (and a password session) are closed
|
|
38
|
+
when you are done::
|
|
39
|
+
|
|
40
|
+
async with AsyncClient("https://erp.example.com", TokenAuth(key, secret)) as client:
|
|
41
|
+
async for todo in client.iter_list("ToDo", filters={"status": "Open"}):
|
|
42
|
+
print(todo["name"])
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
base_url: Root address of the site. Must be ``https://`` unless
|
|
46
|
+
``allow_insecure_http`` is set.
|
|
47
|
+
auth: A :class:`~frappex_client.TokenAuth`, :class:`~frappex_client.BearerAuth` or
|
|
48
|
+
:class:`~frappex_client.PasswordAuth`. Omit it for guest access: no
|
|
49
|
+
credentials are sent, so only what the site opens to guests
|
|
50
|
+
works, such as :meth:`ping`, public files and methods
|
|
51
|
+
whitelisted with ``allow_guest``.
|
|
52
|
+
timeout: Seconds allowed per request, or an ``httpx.Timeout``.
|
|
53
|
+
retry: Retry rules; defaults to :class:`~frappex_client.RetryPolicy`.
|
|
54
|
+
verify: Path of a CA bundle or an ``ssl.SSLContext`` for sites with a
|
|
55
|
+
private certificate. Certificate checks cannot be disabled.
|
|
56
|
+
allow_insecure_http: Permit ``http://`` for a local development site.
|
|
57
|
+
max_response_bytes: Largest response body accepted, after
|
|
58
|
+
decompression.
|
|
59
|
+
headers: Extra headers for every request, such as ``Host`` for a
|
|
60
|
+
multi-site bench. ``Authorization`` and ``Cookie`` are refused.
|
|
61
|
+
transport: An async ``httpx`` transport to use instead of the default, for
|
|
62
|
+
tests or custom networking. It then owns TLS, so ``verify`` no
|
|
63
|
+
longer applies.
|
|
64
|
+
|
|
65
|
+
Raises:
|
|
66
|
+
ConfigurationError: A setting is malformed or unsafe.
|
|
67
|
+
"""
|
|
68
|
+
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
base_url: str,
|
|
72
|
+
auth: Auth | None = None,
|
|
73
|
+
*,
|
|
74
|
+
timeout: float | httpx.Timeout = DEFAULT_TIMEOUT,
|
|
75
|
+
retry: RetryPolicy | None = None,
|
|
76
|
+
verify: ssl.SSLContext | str | os.PathLike[str] | None = None,
|
|
77
|
+
allow_insecure_http: bool = False,
|
|
78
|
+
max_response_bytes: int = DEFAULT_MAX_RESPONSE_BYTES,
|
|
79
|
+
headers: Mapping[str, str] | None = None,
|
|
80
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
81
|
+
) -> None:
|
|
82
|
+
"""Validate the settings and prepare the connection pool."""
|
|
83
|
+
super().__init__(
|
|
84
|
+
base_url,
|
|
85
|
+
auth,
|
|
86
|
+
timeout=timeout,
|
|
87
|
+
retry=retry,
|
|
88
|
+
verify=verify,
|
|
89
|
+
allow_insecure_http=allow_insecure_http,
|
|
90
|
+
max_response_bytes=max_response_bytes,
|
|
91
|
+
headers=headers,
|
|
92
|
+
)
|
|
93
|
+
self._http = httpx.AsyncClient(transport=transport, **self._http_arguments)
|
|
94
|
+
self._login_lock = asyncio.Lock()
|
|
95
|
+
|
|
96
|
+
# -- lifecycle ---------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
async def aclose(self) -> None:
|
|
99
|
+
"""End a password session, if any, and release connections."""
|
|
100
|
+
try:
|
|
101
|
+
if self._logged_in:
|
|
102
|
+
self._logged_in = False
|
|
103
|
+
try:
|
|
104
|
+
await self._run(ops.logout())
|
|
105
|
+
except FrappexError:
|
|
106
|
+
logger.debug("logout failed; the session will expire on its own")
|
|
107
|
+
finally:
|
|
108
|
+
await self._http.aclose()
|
|
109
|
+
|
|
110
|
+
async def __aenter__(self) -> AsyncClient:
|
|
111
|
+
"""Return the client itself."""
|
|
112
|
+
return self
|
|
113
|
+
|
|
114
|
+
async def __aexit__(
|
|
115
|
+
self,
|
|
116
|
+
exc_type: type[BaseException] | None,
|
|
117
|
+
exc: BaseException | None,
|
|
118
|
+
traceback: TracebackType | None,
|
|
119
|
+
) -> None:
|
|
120
|
+
"""Close the client."""
|
|
121
|
+
await self.aclose()
|
|
122
|
+
|
|
123
|
+
# -- transport ---------------------------------------------------------
|
|
124
|
+
|
|
125
|
+
async def _send(self, request: Request) -> RawResponse:
|
|
126
|
+
try:
|
|
127
|
+
async with self._http.stream(
|
|
128
|
+
request.method, request.path, **self._request_arguments(request)
|
|
129
|
+
) as response:
|
|
130
|
+
self._check_declared_length(response.headers, self._max_response_bytes)
|
|
131
|
+
size = ResponseSize(self._max_response_bytes)
|
|
132
|
+
chunks: list[bytes] = []
|
|
133
|
+
async for chunk in response.aiter_bytes(CHUNK_SIZE):
|
|
134
|
+
size.add(len(chunk))
|
|
135
|
+
chunks.append(chunk)
|
|
136
|
+
return RawResponse(response.status_code, response.headers, b"".join(chunks))
|
|
137
|
+
except httpx.HTTPError as exc:
|
|
138
|
+
raise self._transport_error(request, exc) from exc
|
|
139
|
+
|
|
140
|
+
async def _run(self, operation: ops.Operation[T]) -> T:
|
|
141
|
+
request = operation.request
|
|
142
|
+
attempt = 0
|
|
143
|
+
while True:
|
|
144
|
+
attempt += 1
|
|
145
|
+
try:
|
|
146
|
+
response = await self._send(request)
|
|
147
|
+
except TransportError:
|
|
148
|
+
delay = self._retry.delay_after_failure(request.method, attempt)
|
|
149
|
+
if delay is None:
|
|
150
|
+
raise
|
|
151
|
+
else:
|
|
152
|
+
logger.debug("%s %s -> %s", request.method, request.path, response.status_code)
|
|
153
|
+
delay = self._retry.delay_after_response(
|
|
154
|
+
request.method,
|
|
155
|
+
attempt,
|
|
156
|
+
response.status_code,
|
|
157
|
+
parse_retry_after(response.headers),
|
|
158
|
+
)
|
|
159
|
+
if delay is None:
|
|
160
|
+
return operation.parse(decode(response))
|
|
161
|
+
await asyncio.sleep(delay)
|
|
162
|
+
|
|
163
|
+
async def _ensure_session(self) -> None:
|
|
164
|
+
"""Log in once when the client uses password authentication."""
|
|
165
|
+
if self._needs_login:
|
|
166
|
+
async with self._login_lock:
|
|
167
|
+
if self._needs_login and isinstance(self._auth, PasswordAuth):
|
|
168
|
+
await self._run(ops.login(self._auth.username, self._auth.password.reveal()))
|
|
169
|
+
self._logged_in = True
|
|
170
|
+
|
|
171
|
+
async def _execute(self, operation: ops.Operation[T]) -> T:
|
|
172
|
+
await self._ensure_session()
|
|
173
|
+
return await self._run(operation)
|
|
174
|
+
|
|
175
|
+
# -- site --------------------------------------------------------------
|
|
176
|
+
|
|
177
|
+
async def ping(self) -> str:
|
|
178
|
+
"""Check that the site answers. Returns ``"pong"``."""
|
|
179
|
+
return await self._run(ops.ping())
|
|
180
|
+
|
|
181
|
+
async def get_logged_user(self) -> str:
|
|
182
|
+
"""Return the user the credentials belong to.
|
|
183
|
+
|
|
184
|
+
A cheap way to confirm that the credentials work.
|
|
185
|
+
"""
|
|
186
|
+
return await self._execute(ops.get_logged_user())
|
|
187
|
+
|
|
188
|
+
# -- documents ---------------------------------------------------------
|
|
189
|
+
|
|
190
|
+
async def get_list(
|
|
191
|
+
self,
|
|
192
|
+
doctype: str,
|
|
193
|
+
*,
|
|
194
|
+
fields: Sequence[str] | None = None,
|
|
195
|
+
filters: Filters | None = None,
|
|
196
|
+
or_filters: Filters | None = None,
|
|
197
|
+
order_by: str | None = None,
|
|
198
|
+
limit: int = 20,
|
|
199
|
+
offset: int = 0,
|
|
200
|
+
parent: str | None = None,
|
|
201
|
+
) -> list[Document]:
|
|
202
|
+
"""Return one page of documents.
|
|
203
|
+
|
|
204
|
+
Args:
|
|
205
|
+
doctype: DocType to list.
|
|
206
|
+
fields: Fields to return; the site returns only ``name`` if omitted.
|
|
207
|
+
filters: Conditions every row must meet.
|
|
208
|
+
or_filters: Conditions of which a row must meet at least one.
|
|
209
|
+
order_by: Sort clause, such as ``"modified desc"``.
|
|
210
|
+
limit: Maximum rows to return.
|
|
211
|
+
offset: Rows to skip.
|
|
212
|
+
parent: Parent DocType, required when listing a child table.
|
|
213
|
+
|
|
214
|
+
See :meth:`iter_list` to read every matching row.
|
|
215
|
+
"""
|
|
216
|
+
return await self._execute(
|
|
217
|
+
ops.get_list(
|
|
218
|
+
doctype,
|
|
219
|
+
fields=fields,
|
|
220
|
+
filters=filters,
|
|
221
|
+
or_filters=or_filters,
|
|
222
|
+
order_by=order_by,
|
|
223
|
+
limit=limit,
|
|
224
|
+
offset=offset,
|
|
225
|
+
parent=parent,
|
|
226
|
+
)
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
async def iter_list(
|
|
230
|
+
self,
|
|
231
|
+
doctype: str,
|
|
232
|
+
*,
|
|
233
|
+
fields: Sequence[str] | None = None,
|
|
234
|
+
filters: Filters | None = None,
|
|
235
|
+
or_filters: Filters | None = None,
|
|
236
|
+
order_by: str | None = None,
|
|
237
|
+
page_size: int = ops.DEFAULT_PAGE_SIZE,
|
|
238
|
+
parent: str | None = None,
|
|
239
|
+
) -> AsyncIterator[Document]:
|
|
240
|
+
"""Yield every matching document, fetching ``page_size`` rows at a time.
|
|
241
|
+
|
|
242
|
+
Rows are ordered by creation time unless ``order_by`` is given, so
|
|
243
|
+
that documents edited during the iteration are not skipped or
|
|
244
|
+
repeated. Rows created or deleted meanwhile can still shift pages.
|
|
245
|
+
"""
|
|
246
|
+
offset = 0
|
|
247
|
+
while True:
|
|
248
|
+
page = await self.get_list(
|
|
249
|
+
doctype,
|
|
250
|
+
fields=fields,
|
|
251
|
+
filters=filters,
|
|
252
|
+
or_filters=or_filters,
|
|
253
|
+
order_by=order_by or ops.STABLE_ORDER,
|
|
254
|
+
limit=page_size,
|
|
255
|
+
offset=offset,
|
|
256
|
+
parent=parent,
|
|
257
|
+
)
|
|
258
|
+
for document in page:
|
|
259
|
+
yield document
|
|
260
|
+
if len(page) < page_size:
|
|
261
|
+
return
|
|
262
|
+
offset += page_size
|
|
263
|
+
|
|
264
|
+
async def get_doc(self, doctype: str, name: str) -> Document:
|
|
265
|
+
"""Return one document.
|
|
266
|
+
|
|
267
|
+
Raises:
|
|
268
|
+
NotFoundError: No such document.
|
|
269
|
+
"""
|
|
270
|
+
return await self._execute(ops.get_doc(doctype, name))
|
|
271
|
+
|
|
272
|
+
async def insert(self, doctype: str, values: Mapping[str, Any]) -> Document:
|
|
273
|
+
"""Create a document and return it as saved.
|
|
274
|
+
|
|
275
|
+
This request is never retried automatically, because a repeat could
|
|
276
|
+
create a duplicate.
|
|
277
|
+
"""
|
|
278
|
+
return await self._execute(ops.insert(doctype, values))
|
|
279
|
+
|
|
280
|
+
async def update(self, doctype: str, name: str, values: Mapping[str, Any]) -> Document:
|
|
281
|
+
"""Change the given fields of a document and return it as saved."""
|
|
282
|
+
return await self._execute(ops.update(doctype, name, values))
|
|
283
|
+
|
|
284
|
+
async def delete(self, doctype: str, name: str) -> None:
|
|
285
|
+
"""Delete a document."""
|
|
286
|
+
await self._execute(ops.delete(doctype, name))
|
|
287
|
+
|
|
288
|
+
async def submit(self, doctype: str, name: str) -> None:
|
|
289
|
+
"""Submit a draft document."""
|
|
290
|
+
await self._execute(ops.submit(doctype, name))
|
|
291
|
+
|
|
292
|
+
async def cancel(self, doctype: str, name: str) -> None:
|
|
293
|
+
"""Cancel a submitted document."""
|
|
294
|
+
await self._execute(ops.cancel(doctype, name))
|
|
295
|
+
|
|
296
|
+
async def rename(
|
|
297
|
+
self, doctype: str, old_name: str, new_name: str, *, merge: bool = False
|
|
298
|
+
) -> str:
|
|
299
|
+
"""Rename a document and return its new name.
|
|
300
|
+
|
|
301
|
+
Args:
|
|
302
|
+
doctype: DocType of the document.
|
|
303
|
+
old_name: Current name.
|
|
304
|
+
new_name: Name to give it.
|
|
305
|
+
merge: Merge into an existing document called ``new_name``.
|
|
306
|
+
"""
|
|
307
|
+
return await self._execute(ops.rename(doctype, old_name, new_name, merge=merge))
|
|
308
|
+
|
|
309
|
+
async def get_count(self, doctype: str, filters: Filters | None = None) -> int:
|
|
310
|
+
"""Return how many documents match ``filters``."""
|
|
311
|
+
return await self._execute(ops.get_count(doctype, filters))
|
|
312
|
+
|
|
313
|
+
async def get_value(
|
|
314
|
+
self,
|
|
315
|
+
doctype: str,
|
|
316
|
+
fieldname: str | Sequence[str],
|
|
317
|
+
filters: Filters | str | None = None,
|
|
318
|
+
) -> Document | None:
|
|
319
|
+
"""Return the requested fields of the first matching document.
|
|
320
|
+
|
|
321
|
+
Args:
|
|
322
|
+
doctype: DocType to read.
|
|
323
|
+
fieldname: One field name or a list of them.
|
|
324
|
+
filters: Conditions, or a document name.
|
|
325
|
+
|
|
326
|
+
Returns:
|
|
327
|
+
A mapping of field name to value, or ``None`` if nothing matches.
|
|
328
|
+
"""
|
|
329
|
+
return await self._execute(ops.get_value(doctype, fieldname, filters))
|
|
330
|
+
|
|
331
|
+
async def set_value(self, doctype: str, name: str, values: Mapping[str, Any]) -> Document:
|
|
332
|
+
"""Set fields on a document and return it as saved."""
|
|
333
|
+
return await self._execute(ops.set_value(doctype, name, values))
|
|
334
|
+
|
|
335
|
+
# -- methods -----------------------------------------------------------
|
|
336
|
+
|
|
337
|
+
async def call(
|
|
338
|
+
self,
|
|
339
|
+
method: str,
|
|
340
|
+
params: Mapping[str, Any] | None = None,
|
|
341
|
+
*,
|
|
342
|
+
http_method: Literal["GET", "POST"] = "POST",
|
|
343
|
+
) -> Any:
|
|
344
|
+
"""Call a whitelisted server method and return its result.
|
|
345
|
+
|
|
346
|
+
Args:
|
|
347
|
+
method: Dotted path, such as ``"myapp.api.get_summary"``.
|
|
348
|
+
params: Arguments for the method.
|
|
349
|
+
http_method: ``"POST"`` (default) sends the arguments as JSON and
|
|
350
|
+
is never retried. Use ``"GET"`` for a read-only method that is
|
|
351
|
+
safe to repeat.
|
|
352
|
+
"""
|
|
353
|
+
return await self._execute(ops.call(method, params, http_method))
|
|
354
|
+
|
|
355
|
+
# -- files -------------------------------------------------------------
|
|
356
|
+
|
|
357
|
+
async def upload_file(
|
|
358
|
+
self,
|
|
359
|
+
filename: str,
|
|
360
|
+
content: bytes,
|
|
361
|
+
*,
|
|
362
|
+
is_private: bool = True,
|
|
363
|
+
doctype: str | None = None,
|
|
364
|
+
docname: str | None = None,
|
|
365
|
+
fieldname: str | None = None,
|
|
366
|
+
folder: str | None = None,
|
|
367
|
+
) -> Document:
|
|
368
|
+
"""Upload a file and return its ``File`` document.
|
|
369
|
+
|
|
370
|
+
Files are private unless ``is_private=False`` is passed: a public
|
|
371
|
+
file can be fetched by anyone who has its URL.
|
|
372
|
+
|
|
373
|
+
Args:
|
|
374
|
+
filename: Name to store the file under.
|
|
375
|
+
content: File contents.
|
|
376
|
+
is_private: Keep the file behind the site's permissions.
|
|
377
|
+
doctype: DocType of the document to attach the file to.
|
|
378
|
+
docname: Name of the document to attach the file to.
|
|
379
|
+
fieldname: Attach field on that document to fill in.
|
|
380
|
+
folder: Folder in the file manager; the site defaults to ``Home``.
|
|
381
|
+
"""
|
|
382
|
+
return await self._execute(
|
|
383
|
+
ops.upload_file(
|
|
384
|
+
filename,
|
|
385
|
+
content,
|
|
386
|
+
is_private=is_private,
|
|
387
|
+
doctype=doctype,
|
|
388
|
+
docname=docname,
|
|
389
|
+
fieldname=fieldname,
|
|
390
|
+
folder=folder,
|
|
391
|
+
)
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
async def download_to(
|
|
395
|
+
self, file_url: str, target: BinaryIO, *, max_bytes: int | None = None
|
|
396
|
+
) -> int:
|
|
397
|
+
"""Stream a file from the site into ``target``.
|
|
398
|
+
|
|
399
|
+
Args:
|
|
400
|
+
file_url: Site-relative location, such as ``/private/files/a.pdf``
|
|
401
|
+
(the ``file_url`` field of a ``File`` document).
|
|
402
|
+
target: Writable binary file object.
|
|
403
|
+
max_bytes: Stop with :class:`~frappex_client.ResponseTooLargeError` after
|
|
404
|
+
this many bytes; unlimited when omitted.
|
|
405
|
+
|
|
406
|
+
Returns:
|
|
407
|
+
Number of bytes written.
|
|
408
|
+
|
|
409
|
+
A download is not retried, since part of it may already be written.
|
|
410
|
+
"""
|
|
411
|
+
request = Request("GET", file_path(file_url))
|
|
412
|
+
await self._ensure_session()
|
|
413
|
+
try:
|
|
414
|
+
async with self._http.stream("GET", request.path) as response:
|
|
415
|
+
if response.status_code != 200:
|
|
416
|
+
size = ResponseSize(self._max_response_bytes)
|
|
417
|
+
body = bytearray()
|
|
418
|
+
async for chunk in response.aiter_bytes(CHUNK_SIZE):
|
|
419
|
+
size.add(len(chunk))
|
|
420
|
+
body += chunk
|
|
421
|
+
decode(RawResponse(response.status_code, response.headers, bytes(body)))
|
|
422
|
+
raise UnexpectedResponseError(
|
|
423
|
+
f"HTTP {response.status_code}: expected 200 for a download.",
|
|
424
|
+
status_code=response.status_code,
|
|
425
|
+
)
|
|
426
|
+
self._check_declared_length(response.headers, max_bytes)
|
|
427
|
+
size = ResponseSize(max_bytes)
|
|
428
|
+
async for chunk in response.aiter_bytes(CHUNK_SIZE):
|
|
429
|
+
size.add(len(chunk))
|
|
430
|
+
target.write(chunk)
|
|
431
|
+
return size.total
|
|
432
|
+
except httpx.HTTPError as exc:
|
|
433
|
+
raise self._transport_error(request, exc) from exc
|
|
434
|
+
|
|
435
|
+
async def download(self, file_url: str) -> bytes:
|
|
436
|
+
"""Return a file's contents, up to ``max_response_bytes``.
|
|
437
|
+
|
|
438
|
+
Use :meth:`download_to` for large files.
|
|
439
|
+
"""
|
|
440
|
+
buffer = io.BytesIO()
|
|
441
|
+
await self.download_to(file_url, buffer, max_bytes=self._max_response_bytes)
|
|
442
|
+
return buffer.getvalue()
|
frappex_client/_auth.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Credentials and the three ways a client proves who it is.
|
|
2
|
+
|
|
3
|
+
Secrets are wrapped in :class:`Secret` the moment they enter the library, so
|
|
4
|
+
no ``repr``, log line or traceback frame can print them by accident.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
|
|
11
|
+
from .exceptions import ConfigurationError
|
|
12
|
+
|
|
13
|
+
__all__ = ["Auth", "BearerAuth", "PasswordAuth", "Secret", "TokenAuth"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Secret:
|
|
17
|
+
"""A string that never shows its value unless asked to.
|
|
18
|
+
|
|
19
|
+
``repr`` and ``str`` return a mask. Call :meth:`reveal` at the single
|
|
20
|
+
point where the value has to go on the wire.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
__slots__ = ("_value",)
|
|
24
|
+
|
|
25
|
+
def __init__(self, value: str | Secret) -> None:
|
|
26
|
+
"""Wrap ``value``; wrapping a :class:`Secret` again is harmless."""
|
|
27
|
+
raw = value.reveal() if isinstance(value, Secret) else value
|
|
28
|
+
if not isinstance(raw, str) or not raw:
|
|
29
|
+
raise ConfigurationError("A credential must be a non-empty string.")
|
|
30
|
+
if any(ch in raw for ch in "\r\n\x00"):
|
|
31
|
+
raise ConfigurationError("A credential must not contain control characters.")
|
|
32
|
+
self._value = raw
|
|
33
|
+
|
|
34
|
+
def reveal(self) -> str:
|
|
35
|
+
"""Return the wrapped value."""
|
|
36
|
+
return self._value
|
|
37
|
+
|
|
38
|
+
def __repr__(self) -> str:
|
|
39
|
+
"""Return a mask, never the value."""
|
|
40
|
+
return "Secret('********')"
|
|
41
|
+
|
|
42
|
+
__str__ = __repr__
|
|
43
|
+
|
|
44
|
+
def __eq__(self, other: object) -> bool:
|
|
45
|
+
"""Compare by value with another :class:`Secret` only."""
|
|
46
|
+
return isinstance(other, Secret) and other._value == self._value
|
|
47
|
+
|
|
48
|
+
def __hash__(self) -> int:
|
|
49
|
+
"""Hash by value, consistent with ``__eq__``."""
|
|
50
|
+
return hash(self._value)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True, init=False)
|
|
54
|
+
class TokenAuth:
|
|
55
|
+
"""Authenticate with a user's API key and API secret.
|
|
56
|
+
|
|
57
|
+
This is the recommended method for server-to-server use: generate the
|
|
58
|
+
pair under *User > Settings > API Access* on the Frappe site.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
api_key: str
|
|
62
|
+
api_secret: Secret = field(repr=False)
|
|
63
|
+
|
|
64
|
+
def __init__(self, api_key: str, api_secret: str | Secret) -> None:
|
|
65
|
+
"""Validate and wrap the key pair."""
|
|
66
|
+
if not api_key or any(ch in api_key for ch in "\r\n\x00: "):
|
|
67
|
+
raise ConfigurationError("api_key is empty or contains illegal characters.")
|
|
68
|
+
object.__setattr__(self, "api_key", api_key)
|
|
69
|
+
object.__setattr__(self, "api_secret", Secret(api_secret))
|
|
70
|
+
|
|
71
|
+
def headers(self) -> dict[str, str]:
|
|
72
|
+
"""Return the ``Authorization`` header for this key pair."""
|
|
73
|
+
return {"Authorization": f"token {self.api_key}:{self.api_secret.reveal()}"}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True, init=False)
|
|
77
|
+
class BearerAuth:
|
|
78
|
+
"""Authenticate with an OAuth 2 access token issued by the Frappe site."""
|
|
79
|
+
|
|
80
|
+
token: Secret = field(repr=False)
|
|
81
|
+
|
|
82
|
+
def __init__(self, token: str | Secret) -> None:
|
|
83
|
+
"""Validate and wrap the access token."""
|
|
84
|
+
object.__setattr__(self, "token", Secret(token))
|
|
85
|
+
|
|
86
|
+
def headers(self) -> dict[str, str]:
|
|
87
|
+
"""Return the ``Authorization`` header for this token."""
|
|
88
|
+
return {"Authorization": f"Bearer {self.token.reveal()}"}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass(frozen=True, init=False)
|
|
92
|
+
class PasswordAuth:
|
|
93
|
+
"""Authenticate with a username and password (cookie session).
|
|
94
|
+
|
|
95
|
+
The client logs in on its first request and logs out when closed. Prefer
|
|
96
|
+
:class:`TokenAuth` for unattended programs: it needs no login round trip
|
|
97
|
+
and the key can be revoked without changing the user's password.
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
username: str
|
|
101
|
+
password: Secret = field(repr=False)
|
|
102
|
+
|
|
103
|
+
def __init__(self, username: str, password: str | Secret) -> None:
|
|
104
|
+
"""Validate and wrap the login details."""
|
|
105
|
+
if not username:
|
|
106
|
+
raise ConfigurationError("username must not be empty.")
|
|
107
|
+
object.__setattr__(self, "username", username)
|
|
108
|
+
object.__setattr__(self, "password", Secret(password))
|
|
109
|
+
|
|
110
|
+
def headers(self) -> dict[str, str]:
|
|
111
|
+
"""Return no headers: the session cookie carries the identity."""
|
|
112
|
+
return {}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
Auth = TokenAuth | BearerAuth | PasswordAuth
|
|
116
|
+
"""Any of the supported authentication strategies."""
|