das-cli 1.6.0__tar.gz → 1.6.6__tar.gz
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.
- {das_cli-1.6.0/das_cli.egg-info → das_cli-1.6.6}/PKG-INFO +15 -1
- {das_cli-1.6.0 → das_cli-1.6.6}/README.md +14 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/cli.py +48 -20
- {das_cli-1.6.0 → das_cli-1.6.6}/das/common/api.py +23 -8
- das_cli-1.6.6/das/common/errors.py +165 -0
- das_cli-1.6.6/das/common/exceptions.py +191 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/managers/entries_manager.py +107 -19
- {das_cli-1.6.0 → das_cli-1.6.6}/das/services/digital_objects.py +52 -9
- {das_cli-1.6.0 → das_cli-1.6.6/das_cli.egg-info}/PKG-INFO +15 -1
- {das_cli-1.6.0 → das_cli-1.6.6}/das_cli.egg-info/SOURCES.txt +1 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/pyproject.toml +1 -1
- das_cli-1.6.0/das/common/errors.py +0 -93
- {das_cli-1.6.0 → das_cli-1.6.6}/LICENSE +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/MANIFEST.in +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/__init__.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/ai/plugins/dasai.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/ai/plugins/entries/entries_plugin.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/app.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/authentication/auth.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/authentication/oauth.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/authentication/secure_input.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/common/config.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/common/entry_fields_constants.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/common/enums.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/common/file_utils.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/managers/__init__.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/managers/digital_objects_manager.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/managers/download_manager.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/managers/search_manager.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/services/attributes.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/services/cache.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/services/das_elastic_search.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/services/downloads.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/services/entries.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/services/entry_fields.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/services/hangfire.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/services/search.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/services/service_base.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das/services/users.py +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das_cli.egg-info/dependency_links.txt +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das_cli.egg-info/entry_points.txt +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das_cli.egg-info/requires.txt +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/das_cli.egg-info/top_level.txt +0 -0
- {das_cli-1.6.0 → das_cli-1.6.6}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: das-cli
|
|
3
|
-
Version: 1.6.
|
|
3
|
+
Version: 1.6.6
|
|
4
4
|
Summary: DAS api client.
|
|
5
5
|
Author: Royal Netherlands Institute for Sea Research
|
|
6
6
|
License-Expression: MIT
|
|
@@ -362,6 +362,20 @@ entry = entries.get(id="6b0e68e6-00cd-43a7-9c51-d56c9c091123")
|
|
|
362
362
|
entry = entries.get_entry("6b0e68e6-00cd-43a7-9c51-d56c9c091123")
|
|
363
363
|
```
|
|
364
364
|
|
|
365
|
+
When the entry has digital objects attached they are always included, even for
|
|
366
|
+
attributes whose entry-field metadata does not expose a digital-object field.
|
|
367
|
+
They land under the digital-object field's display name when there is one, and
|
|
368
|
+
under `"Digital Object(s)"` otherwise:
|
|
369
|
+
|
|
370
|
+
```python
|
|
371
|
+
for obj in entry.get("Digital Object(s)", []):
|
|
372
|
+
print(obj["Id"], obj["Name"], obj["Type"], obj["Links"])
|
|
373
|
+
# 1715e27d-bc89-4f9c-8fdf-36ad2da333c6 zeynep.erdem.jpg Image 4d.b.cb
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
`das entry get` and `das search entry <id>` print the same objects as a block
|
|
377
|
+
below the field list (or inline in the payload with `--format json`).
|
|
378
|
+
|
|
365
379
|
#### `create` — create one or many entries
|
|
366
380
|
|
|
367
381
|
```python
|
|
@@ -339,6 +339,20 @@ entry = entries.get(id="6b0e68e6-00cd-43a7-9c51-d56c9c091123")
|
|
|
339
339
|
entry = entries.get_entry("6b0e68e6-00cd-43a7-9c51-d56c9c091123")
|
|
340
340
|
```
|
|
341
341
|
|
|
342
|
+
When the entry has digital objects attached they are always included, even for
|
|
343
|
+
attributes whose entry-field metadata does not expose a digital-object field.
|
|
344
|
+
They land under the digital-object field's display name when there is one, and
|
|
345
|
+
under `"Digital Object(s)"` otherwise:
|
|
346
|
+
|
|
347
|
+
```python
|
|
348
|
+
for obj in entry.get("Digital Object(s)", []):
|
|
349
|
+
print(obj["Id"], obj["Name"], obj["Type"], obj["Links"])
|
|
350
|
+
# 1715e27d-bc89-4f9c-8fdf-36ad2da333c6 zeynep.erdem.jpg Image 4d.b.cb
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
`das entry get` and `das search entry <id>` print the same objects as a block
|
|
354
|
+
below the field list (or inline in the payload with `--format json`).
|
|
355
|
+
|
|
342
356
|
#### `create` — create one or many entries
|
|
343
357
|
|
|
344
358
|
```python
|
|
@@ -53,6 +53,32 @@ def format_table(data, headers):
|
|
|
53
53
|
|
|
54
54
|
return '\n'.join(table)
|
|
55
55
|
|
|
56
|
+
def is_digital_object_list(value):
|
|
57
|
+
"""True when a manager field value is a list of digital objects.
|
|
58
|
+
|
|
59
|
+
Digital objects are normalized to Id/Name/Links/Type by the entry manager;
|
|
60
|
+
select/relation fields only ever carry Id/Name, so "Type" tells them apart.
|
|
61
|
+
"""
|
|
62
|
+
return (
|
|
63
|
+
isinstance(value, list)
|
|
64
|
+
and len(value) > 0
|
|
65
|
+
and all(isinstance(item, dict) and "Id" in item and "Type" in item for item in value)
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def echo_digital_objects(label, objects):
|
|
70
|
+
"""Print a digital-object list as an indented block."""
|
|
71
|
+
click.echo()
|
|
72
|
+
click.echo("─" * 40)
|
|
73
|
+
click.echo(f"{label}:")
|
|
74
|
+
for obj in objects:
|
|
75
|
+
click.echo(f" - ID: {obj.get('Id')}")
|
|
76
|
+
click.echo(f" Name: {obj.get('Name')}")
|
|
77
|
+
click.echo(f" Type: {obj.get('Type')}")
|
|
78
|
+
click.echo(f" Links: {obj.get('Links')}")
|
|
79
|
+
click.echo()
|
|
80
|
+
|
|
81
|
+
|
|
56
82
|
class DasCLI:
|
|
57
83
|
def __init__(self):
|
|
58
84
|
self.client = None
|
|
@@ -378,11 +404,17 @@ def get_entry(das_ctx, entry_id, output_format):
|
|
|
378
404
|
|
|
379
405
|
# Format display fields in a readable way
|
|
380
406
|
formatted_data = []
|
|
407
|
+
digital_object_blocks = []
|
|
381
408
|
for key, value in sorted(entry.items()):
|
|
382
409
|
# Skip empty or None values
|
|
383
410
|
if value is None or value == '':
|
|
384
411
|
continue
|
|
385
|
-
|
|
412
|
+
|
|
413
|
+
# Digital objects get their own block below the key/value list
|
|
414
|
+
if is_digital_object_list(value):
|
|
415
|
+
digital_object_blocks.append((key, value))
|
|
416
|
+
continue
|
|
417
|
+
|
|
386
418
|
# Format date fields
|
|
387
419
|
if isinstance(value, str) and key.lower().endswith(('time', 'date')) and 'T' in value:
|
|
388
420
|
try:
|
|
@@ -398,7 +430,10 @@ def get_entry(das_ctx, entry_id, output_format):
|
|
|
398
430
|
# Display as key-value pairs
|
|
399
431
|
for key, value in formatted_data:
|
|
400
432
|
click.echo(f"{key.ljust(25)}: {value}")
|
|
401
|
-
|
|
433
|
+
|
|
434
|
+
for key, objects in digital_object_blocks:
|
|
435
|
+
echo_digital_objects(key, objects)
|
|
436
|
+
|
|
402
437
|
except Exception as e:
|
|
403
438
|
click.secho(f"Error: {e}", fg="red")
|
|
404
439
|
|
|
@@ -856,7 +891,7 @@ def direct_download_digital_object(das_ctx, entry_code, entry_id, attribute_id,
|
|
|
856
891
|
|
|
857
892
|
@entry.command("get")
|
|
858
893
|
@click.option('--code', default=None, help='Entry code')
|
|
859
|
-
@click.option('--id',
|
|
894
|
+
@click.option('--id', default=None, help='Entry ID (GUID)')
|
|
860
895
|
@pass_das_context
|
|
861
896
|
def get_entry(das_ctx, code=None, id=None):
|
|
862
897
|
"""Get entry by either its code or ID"""
|
|
@@ -872,28 +907,21 @@ def get_entry(das_ctx, code=None, id=None):
|
|
|
872
907
|
if entry:
|
|
873
908
|
click.secho("Entry Details:", fg="green", bold=True)
|
|
874
909
|
click.echo("─" * 40)
|
|
910
|
+
digital_object_blocks = []
|
|
875
911
|
for key, value in entry.items():
|
|
876
|
-
if
|
|
877
|
-
|
|
878
|
-
|
|
912
|
+
if is_digital_object_list(value):
|
|
913
|
+
# printed as its own block below, for readability
|
|
914
|
+
digital_object_blocks.append((key, value))
|
|
915
|
+
elif isinstance(value, list):
|
|
879
916
|
click.echo(f"{key}:")
|
|
880
917
|
for item in value:
|
|
881
|
-
click.echo(f" - {item}")
|
|
882
|
-
else:
|
|
918
|
+
click.echo(f" - {item}")
|
|
919
|
+
else:
|
|
883
920
|
click.echo(f"{key}: {value or ''}")
|
|
884
921
|
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
click.echo()
|
|
889
|
-
click.echo("─" * 40)
|
|
890
|
-
click.echo("Digital Object(s):")
|
|
891
|
-
for obj in entry['Digital Object(s)']:
|
|
892
|
-
click.echo(f" - ID: {obj.get('Id')}")
|
|
893
|
-
click.echo(f" Name: {obj.get('Name')}")
|
|
894
|
-
click.echo(f" Type: {obj.get('Type')}")
|
|
895
|
-
click.echo(f" Links: {obj.get('Links')}")
|
|
896
|
-
click.echo()
|
|
922
|
+
for key, objects in digital_object_blocks:
|
|
923
|
+
echo_digital_objects(key, objects)
|
|
924
|
+
|
|
897
925
|
click.echo("─" * 40)
|
|
898
926
|
else:
|
|
899
927
|
click.secho("Entry not found.", fg="yellow")
|
|
@@ -24,6 +24,10 @@ def _process_response(response, action: str):
|
|
|
24
24
|
# behaviour does not depend on ``.ok`` being populated.
|
|
25
25
|
is_http_error = response.status_code >= 400
|
|
26
26
|
|
|
27
|
+
# The server tags every response with a correlation id; carry it along so
|
|
28
|
+
# error messages can quote it (invaluable for tracing 5xx server-side).
|
|
29
|
+
correlation_id = response.headers.get("X-Correlation-ID")
|
|
30
|
+
|
|
27
31
|
try:
|
|
28
32
|
data = response.json()
|
|
29
33
|
except json.JSONDecodeError as json_err:
|
|
@@ -33,26 +37,37 @@ def _process_response(response, action: str):
|
|
|
33
37
|
f"The server returned HTTP {response.status_code} "
|
|
34
38
|
f"({response.reason}) while trying to {action}."
|
|
35
39
|
)
|
|
36
|
-
logger.error(
|
|
40
|
+
logger.error(
|
|
41
|
+
"%s Response body: %s [correlationId: %s]",
|
|
42
|
+
message, response.text[:500], correlation_id,
|
|
43
|
+
)
|
|
37
44
|
return {
|
|
38
45
|
"error": message,
|
|
39
46
|
"status_code": response.status_code,
|
|
47
|
+
"correlation_id": correlation_id,
|
|
40
48
|
"raw_content": response.text[:500],
|
|
41
49
|
}
|
|
42
50
|
logger.error("Error decoding JSON response: %s", json_err)
|
|
43
51
|
return {
|
|
44
52
|
"error": f"Invalid JSON response: {json_err}",
|
|
45
53
|
"status_code": response.status_code,
|
|
54
|
+
"correlation_id": correlation_id,
|
|
46
55
|
"raw_content": response.text[:500],
|
|
47
56
|
}
|
|
48
57
|
|
|
49
|
-
if isinstance(data, dict)
|
|
50
|
-
# ABP usually returns 200 even for logical errors,
|
|
51
|
-
#
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
"
|
|
55
|
-
)
|
|
58
|
+
if isinstance(data, dict):
|
|
59
|
+
# ABP usually returns 200 even for logical errors, so attach the status
|
|
60
|
+
# code when the HTTP layer itself signalled an error, and the
|
|
61
|
+
# correlation id whenever the call failed by either signal.
|
|
62
|
+
if is_http_error:
|
|
63
|
+
data.setdefault("status_code", response.status_code)
|
|
64
|
+
if correlation_id and (is_http_error or data.get("success") is False):
|
|
65
|
+
data.setdefault("correlation_id", correlation_id)
|
|
66
|
+
if is_http_error:
|
|
67
|
+
logger.debug(
|
|
68
|
+
"%s returned HTTP %s: %s [correlationId: %s]",
|
|
69
|
+
action, response.status_code, data.get("error"), correlation_id,
|
|
70
|
+
)
|
|
56
71
|
return data
|
|
57
72
|
|
|
58
73
|
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Shared helpers for turning HTTP/API failures into clear, human-readable messages.
|
|
2
|
+
|
|
3
|
+
The goal is to never surface a raw stack trace or a raw Python dict/JSON blob to
|
|
4
|
+
the user. Instead we extract the message the API actually returned (ABP wraps it
|
|
5
|
+
in an ``error`` object), classify it by HTTP status (4xx vs 5xx) and add an
|
|
6
|
+
actionable hint plus the server correlation id so users and developers can tell
|
|
7
|
+
at a glance *why* a call failed and what to do next.
|
|
8
|
+
|
|
9
|
+
Two entry points:
|
|
10
|
+
|
|
11
|
+
* :func:`build_api_error` returns a typed :class:`~das.common.exceptions.DasApiError`
|
|
12
|
+
(``DasAuthenticationError``, ``DasValidationError``, ``DasServerError`` …) that
|
|
13
|
+
callers can raise and, if they wish, catch by type.
|
|
14
|
+
* :func:`extract_api_error` returns the same information as a ready-to-print
|
|
15
|
+
string. It is kept for the many call sites that do
|
|
16
|
+
``raise ValueError(extract_api_error(response))``.
|
|
17
|
+
"""
|
|
18
|
+
import logging
|
|
19
|
+
|
|
20
|
+
import requests
|
|
21
|
+
|
|
22
|
+
from das.common.exceptions import DasApiError, DasConnectionError, DasServerError, for_status
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger("das")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def describe_request_exception(exc: Exception, url: str = None) -> str:
|
|
28
|
+
"""Return a friendly message for a ``requests`` exception.
|
|
29
|
+
|
|
30
|
+
Distinguishes the common connection-level failures (bad/self-signed TLS
|
|
31
|
+
certificate, host unreachable, timeout) so the user gets an actionable hint
|
|
32
|
+
instead of an opaque traceback.
|
|
33
|
+
"""
|
|
34
|
+
where = f" ({url})" if url else ""
|
|
35
|
+
|
|
36
|
+
if isinstance(exc, requests.exceptions.SSLError):
|
|
37
|
+
return (
|
|
38
|
+
"SSL certificate verification failed for the server"
|
|
39
|
+
f"{where}. The host may be using a self-signed or otherwise "
|
|
40
|
+
"untrusted certificate. If you trust this host, disable "
|
|
41
|
+
"verification with 'das config ssl-verify false'. "
|
|
42
|
+
f"Details: {exc}"
|
|
43
|
+
)
|
|
44
|
+
if isinstance(exc, requests.exceptions.ConnectTimeout):
|
|
45
|
+
return f"Timed out while connecting to the server{where}. Details: {exc}"
|
|
46
|
+
if isinstance(exc, requests.exceptions.ReadTimeout):
|
|
47
|
+
return f"The server{where} took too long to respond. Details: {exc}"
|
|
48
|
+
if isinstance(exc, requests.exceptions.Timeout):
|
|
49
|
+
return f"The request timed out{where}. Details: {exc}"
|
|
50
|
+
if isinstance(exc, requests.exceptions.ConnectionError):
|
|
51
|
+
return (
|
|
52
|
+
f"Could not connect to the server{where}. Check that the API URL is "
|
|
53
|
+
"correct and that the host is reachable. "
|
|
54
|
+
f"Details: {exc}"
|
|
55
|
+
)
|
|
56
|
+
return str(exc)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def connection_error(exc: Exception, url: str = None) -> DasConnectionError:
|
|
60
|
+
"""Wrap a ``requests`` transport exception as a typed connection error.
|
|
61
|
+
|
|
62
|
+
Unlike responses routed through :mod:`das.common.api` (which log their own
|
|
63
|
+
transport failures), callers that issue requests directly — e.g. the chunked
|
|
64
|
+
file upload — rely on this helper, so log here to keep coverage uniform.
|
|
65
|
+
"""
|
|
66
|
+
error = DasConnectionError(describe_request_exception(exc, url))
|
|
67
|
+
logger.debug("Connection error: %s", str(error).replace("\n", " | "))
|
|
68
|
+
return error
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _parse_response(response, default: str):
|
|
72
|
+
"""Pull message / details / validation errors / status / correlation id out
|
|
73
|
+
of a parsed API response dict.
|
|
74
|
+
|
|
75
|
+
Returns a tuple ``(message, details, validation_errors, status_code,
|
|
76
|
+
correlation_id)``.
|
|
77
|
+
"""
|
|
78
|
+
if not isinstance(response, dict):
|
|
79
|
+
text = str(response).strip()
|
|
80
|
+
return (text or default, None, [], None, None)
|
|
81
|
+
|
|
82
|
+
status_code = response.get("status_code")
|
|
83
|
+
correlation_id = response.get("correlation_id")
|
|
84
|
+
|
|
85
|
+
error = response.get("error")
|
|
86
|
+
|
|
87
|
+
message = ""
|
|
88
|
+
details = None
|
|
89
|
+
validation_errors = []
|
|
90
|
+
|
|
91
|
+
if isinstance(error, dict):
|
|
92
|
+
message = (error.get("message") or "").strip()
|
|
93
|
+
details = (error.get("details") or "").strip() or None
|
|
94
|
+
|
|
95
|
+
raw_validation = error.get("validationErrors")
|
|
96
|
+
if isinstance(raw_validation, list):
|
|
97
|
+
for item in raw_validation:
|
|
98
|
+
if isinstance(item, dict) and item.get("message"):
|
|
99
|
+
validation_errors.append(str(item["message"]).strip())
|
|
100
|
+
elif isinstance(item, str) and item.strip():
|
|
101
|
+
validation_errors.append(item.strip())
|
|
102
|
+
|
|
103
|
+
# The error object may carry the correlation id too (fallback middleware).
|
|
104
|
+
correlation_id = correlation_id or error.get("correlationId")
|
|
105
|
+
elif isinstance(error, str) and error.strip():
|
|
106
|
+
message = error.strip()
|
|
107
|
+
|
|
108
|
+
if not message:
|
|
109
|
+
# No structured message but the call still failed (e.g. a non-JSON body
|
|
110
|
+
# surfaced by das.common.api).
|
|
111
|
+
raw = response.get("raw_content")
|
|
112
|
+
message = str(raw).strip() if raw else ""
|
|
113
|
+
|
|
114
|
+
return (message or default, details, validation_errors, status_code, correlation_id)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def build_api_error(response, default: str = "Unknown error occurred") -> DasApiError:
|
|
118
|
+
"""Build a typed :class:`DasApiError` from a parsed API response.
|
|
119
|
+
|
|
120
|
+
The concrete subclass is chosen from the HTTP status code (and the presence
|
|
121
|
+
of validation errors), so callers can distinguish 4xx from 5xx by type as
|
|
122
|
+
well as by the rendered message.
|
|
123
|
+
"""
|
|
124
|
+
message, details, validation_errors, status_code, correlation_id = _parse_response(
|
|
125
|
+
response, default
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
error_cls = for_status(status_code, has_validation_errors=bool(validation_errors))
|
|
129
|
+
error = error_cls(
|
|
130
|
+
message,
|
|
131
|
+
status_code=status_code,
|
|
132
|
+
correlation_id=correlation_id,
|
|
133
|
+
details=details,
|
|
134
|
+
validation_errors=validation_errors,
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
# Log every surfaced API error here — the single choke point all callers go
|
|
138
|
+
# through — so the full categorised message and correlation id land in the
|
|
139
|
+
# log (invaluable for tracing a 5xx). Logged at DEBUG on purpose: the CLI
|
|
140
|
+
# already prints a friendly message to the console, so logging louder would
|
|
141
|
+
# double-print it (the ``das`` logger propagates to the default WARNING
|
|
142
|
+
# console handler). Enable capture with ``das config log-level debug`` or a
|
|
143
|
+
# debug-level log file. ``severity`` records the true level for readers.
|
|
144
|
+
severity = "ERROR" if isinstance(error, DasServerError) else "WARNING"
|
|
145
|
+
logger.debug(
|
|
146
|
+
"API error [severity=%s status=%s correlationId=%s]: %s",
|
|
147
|
+
severity,
|
|
148
|
+
error.status_code,
|
|
149
|
+
error.correlation_id,
|
|
150
|
+
str(error).replace("\n", " | "),
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
return error
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def extract_api_error(response, default: str = "Unknown error occurred") -> str:
|
|
157
|
+
"""Extract a human-readable, category-aware error message from a response.
|
|
158
|
+
|
|
159
|
+
Backward-compatible string form of :func:`build_api_error`. Handles the ABP
|
|
160
|
+
envelope as well as the plain-string errors produced by :mod:`das.common.api`.
|
|
161
|
+
The returned message is prefixed with the HTTP status and an error category
|
|
162
|
+
(e.g. ``HTTP 404 — Not found: ...``) and, for server errors, includes the
|
|
163
|
+
correlation id to quote to support.
|
|
164
|
+
"""
|
|
165
|
+
return str(build_api_error(response, default))
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Typed exceptions for DAS API failures.
|
|
2
|
+
|
|
3
|
+
The DAS backend returns errors in ABP's envelope
|
|
4
|
+
(``{"success": false, "error": {"message", "details", "validationErrors"}}``)
|
|
5
|
+
together with an HTTP status code and an ``X-Correlation-ID`` header. These
|
|
6
|
+
classes turn that raw data into clear, category-specific messages so both end
|
|
7
|
+
users and developers can immediately tell *why* a call failed and what to do
|
|
8
|
+
about it — in particular whether it is a 4xx (fix your request) or a 5xx
|
|
9
|
+
(server-side fault, quote the reference).
|
|
10
|
+
|
|
11
|
+
All classes derive from :class:`ValueError` so that existing ``except
|
|
12
|
+
ValueError`` / ``except Exception`` handlers throughout the CLI keep working;
|
|
13
|
+
they simply receive a richer message (and, when caught by type, the HTTP
|
|
14
|
+
status code and correlation id as attributes).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DasApiError(ValueError):
|
|
19
|
+
"""Base class for an error returned by the DAS API.
|
|
20
|
+
|
|
21
|
+
Attributes:
|
|
22
|
+
api_message: The raw message extracted from the API response.
|
|
23
|
+
status_code: The HTTP status code, if known.
|
|
24
|
+
correlation_id: The server correlation id (``X-Correlation-ID``), if any.
|
|
25
|
+
details: Extra detail text returned alongside the message.
|
|
26
|
+
validation_errors: List of field-level validation messages.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
#: Short human label used in the rendered message.
|
|
30
|
+
category = "API error"
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
message,
|
|
35
|
+
*,
|
|
36
|
+
status_code=None,
|
|
37
|
+
correlation_id=None,
|
|
38
|
+
details=None,
|
|
39
|
+
validation_errors=None,
|
|
40
|
+
):
|
|
41
|
+
self.api_message = (message or "").strip() or "Unknown error occurred"
|
|
42
|
+
self.status_code = status_code
|
|
43
|
+
self.correlation_id = correlation_id
|
|
44
|
+
self.details = (details or "").strip() or None
|
|
45
|
+
self.validation_errors = [v for v in (validation_errors or []) if v]
|
|
46
|
+
super().__init__(self._render())
|
|
47
|
+
|
|
48
|
+
# -- rendering ---------------------------------------------------------
|
|
49
|
+
|
|
50
|
+
def guidance(self):
|
|
51
|
+
"""Return an actionable hint for this error class, or None."""
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
def _render(self):
|
|
55
|
+
# Only decorate with the category when we actually have something to
|
|
56
|
+
# categorise by — a status code, or a specific (non-base) error type.
|
|
57
|
+
# Otherwise (e.g. an ABP logical error returned with HTTP 200 and no
|
|
58
|
+
# status) show the bare message so it stays clean.
|
|
59
|
+
if self.status_code:
|
|
60
|
+
header = f"HTTP {self.status_code} — {self.category}: {self.api_message}"
|
|
61
|
+
elif type(self) is not DasApiError:
|
|
62
|
+
header = f"{self.category}: {self.api_message}"
|
|
63
|
+
else:
|
|
64
|
+
header = self.api_message
|
|
65
|
+
|
|
66
|
+
lines = [header]
|
|
67
|
+
|
|
68
|
+
if self.details and self.details != self.api_message:
|
|
69
|
+
lines.append(self.details)
|
|
70
|
+
|
|
71
|
+
for item in self.validation_errors:
|
|
72
|
+
lines.append(f" • {item}")
|
|
73
|
+
|
|
74
|
+
hint = self.guidance()
|
|
75
|
+
if hint:
|
|
76
|
+
lines.append(hint)
|
|
77
|
+
|
|
78
|
+
if self.correlation_id:
|
|
79
|
+
lines.append(f"Reference: {self.correlation_id}")
|
|
80
|
+
|
|
81
|
+
return "\n".join(lines)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class DasAuthenticationError(DasApiError):
|
|
85
|
+
"""401 — the caller is not authenticated (missing/expired credentials)."""
|
|
86
|
+
|
|
87
|
+
category = "Authentication error"
|
|
88
|
+
|
|
89
|
+
def guidance(self):
|
|
90
|
+
return (
|
|
91
|
+
"Your credentials are missing or have expired. Re-authenticate with "
|
|
92
|
+
"'das auth login', or verify the API key you configured."
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class DasPermissionError(DasApiError):
|
|
97
|
+
"""403 — authenticated but not authorized for this action."""
|
|
98
|
+
|
|
99
|
+
category = "Permission error"
|
|
100
|
+
|
|
101
|
+
def guidance(self):
|
|
102
|
+
return (
|
|
103
|
+
"You are signed in but lack permission for this action. Check your "
|
|
104
|
+
"role/permissions, or that your API key is scoped for it."
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class DasNotFoundError(DasApiError):
|
|
109
|
+
"""404 — the requested resource does not exist."""
|
|
110
|
+
|
|
111
|
+
category = "Not found"
|
|
112
|
+
|
|
113
|
+
def guidance(self):
|
|
114
|
+
return "Check the id/code is correct and that the resource still exists."
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class DasValidationError(DasApiError):
|
|
118
|
+
"""400/422 — the request was rejected as invalid."""
|
|
119
|
+
|
|
120
|
+
category = "Validation error"
|
|
121
|
+
|
|
122
|
+
def guidance(self):
|
|
123
|
+
return "Correct the field(s) above and try again."
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class DasConflictError(DasApiError):
|
|
127
|
+
"""409 — the request conflicts with the current server state."""
|
|
128
|
+
|
|
129
|
+
category = "Conflict"
|
|
130
|
+
|
|
131
|
+
def guidance(self):
|
|
132
|
+
return (
|
|
133
|
+
"This conflicts with existing data (e.g. a duplicate key) or a "
|
|
134
|
+
"concurrent change. Reload the current state and retry."
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class DasClientError(DasApiError):
|
|
139
|
+
"""Other 4xx — a client-side problem not covered by a more specific class."""
|
|
140
|
+
|
|
141
|
+
category = "Request error"
|
|
142
|
+
|
|
143
|
+
def guidance(self):
|
|
144
|
+
return "The server rejected the request. Review the parameters and retry."
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class DasServerError(DasApiError):
|
|
148
|
+
"""5xx — a server-side fault, not caused by the caller's input."""
|
|
149
|
+
|
|
150
|
+
category = "Server error"
|
|
151
|
+
|
|
152
|
+
def guidance(self):
|
|
153
|
+
base = (
|
|
154
|
+
"This is a server-side problem, not caused by your request. Wait a "
|
|
155
|
+
"moment and retry."
|
|
156
|
+
)
|
|
157
|
+
if self.correlation_id:
|
|
158
|
+
return base + " If it persists, contact support and quote the reference below."
|
|
159
|
+
return base + " If it persists, contact support with the time of the request."
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class DasConnectionError(DasApiError):
|
|
163
|
+
"""The request never reached the server (DNS/TLS/timeout/connection refused)."""
|
|
164
|
+
|
|
165
|
+
category = "Connection error"
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
# Status code -> exception class. 400 is resolved dynamically (validation vs
|
|
169
|
+
# generic) in :func:`for_status`.
|
|
170
|
+
_STATUS_MAP = {
|
|
171
|
+
401: DasAuthenticationError,
|
|
172
|
+
403: DasPermissionError,
|
|
173
|
+
404: DasNotFoundError,
|
|
174
|
+
409: DasConflictError,
|
|
175
|
+
422: DasValidationError,
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def for_status(status_code, has_validation_errors=False):
|
|
180
|
+
"""Return the most specific :class:`DasApiError` subclass for a status code."""
|
|
181
|
+
if status_code in _STATUS_MAP:
|
|
182
|
+
return _STATUS_MAP[status_code]
|
|
183
|
+
if status_code == 400:
|
|
184
|
+
return DasValidationError if has_validation_errors else DasClientError
|
|
185
|
+
if isinstance(status_code, int):
|
|
186
|
+
if status_code >= 500:
|
|
187
|
+
return DasServerError
|
|
188
|
+
if status_code >= 400:
|
|
189
|
+
return DasClientError
|
|
190
|
+
# Unknown / no status (e.g. ABP logical error returned with HTTP 200).
|
|
191
|
+
return DasValidationError if has_validation_errors else DasApiError
|
|
@@ -49,6 +49,54 @@ def _safe_lower(value) -> str:
|
|
|
49
49
|
return str(value).lower()
|
|
50
50
|
|
|
51
51
|
|
|
52
|
+
# Key used for digital objects when the attribute's entry-field metadata does
|
|
53
|
+
# not expose a DIGITAL_OBJECT_INPUT field (the CLI already prints this name).
|
|
54
|
+
DIGITAL_OBJECTS_KEY = "Digital Object(s)"
|
|
55
|
+
|
|
56
|
+
# Keys only a digital-object payload carries. Select/relation attributes are
|
|
57
|
+
# also returned as JSON lists under numeric keys, but they only ever hold
|
|
58
|
+
# id/name/attributeid/tag - so these markers tell the two apart.
|
|
59
|
+
_DIGITAL_OBJECT_MARKERS = ("filesize", "checksum", "instrumentname", "path")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _normalize_digital_object(obj: dict) -> dict:
|
|
63
|
+
"""Reduce a raw digital-object payload to the fields we surface."""
|
|
64
|
+
return {
|
|
65
|
+
"Id": obj.get("id"),
|
|
66
|
+
"Name": obj.get("name"),
|
|
67
|
+
"Links": obj.get("needle"),
|
|
68
|
+
"Type": obj.get("typename"),
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _parse_digital_objects(value):
|
|
73
|
+
"""Parse a raw entry value into a list of normalized digital objects.
|
|
74
|
+
|
|
75
|
+
Returns ``None`` when the value is not a JSON list of digital objects, so
|
|
76
|
+
callers can safely walk every value of an entry payload.
|
|
77
|
+
"""
|
|
78
|
+
if not isinstance(value, str) or value.strip() == "":
|
|
79
|
+
return None
|
|
80
|
+
|
|
81
|
+
try:
|
|
82
|
+
data = json.loads(value)
|
|
83
|
+
except ValueError: # includes json.JSONDecodeError
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
if not isinstance(data, list):
|
|
87
|
+
return None
|
|
88
|
+
|
|
89
|
+
objects = [obj for obj in data if isinstance(obj, dict)]
|
|
90
|
+
|
|
91
|
+
if not objects:
|
|
92
|
+
return None
|
|
93
|
+
|
|
94
|
+
if not any(marker in obj for obj in objects for marker in _DIGITAL_OBJECT_MARKERS):
|
|
95
|
+
return None
|
|
96
|
+
|
|
97
|
+
return [_normalize_digital_object(obj) for obj in objects]
|
|
98
|
+
|
|
99
|
+
|
|
52
100
|
class EntryManager:
|
|
53
101
|
def __init__(self):
|
|
54
102
|
|
|
@@ -160,6 +208,8 @@ class EntryManager:
|
|
|
160
208
|
|
|
161
209
|
entry[field_name] = field_value
|
|
162
210
|
|
|
211
|
+
self.__attach_digital_objects(entry, entry_raw, fields.get("result").get("items"))
|
|
212
|
+
|
|
163
213
|
if (entry_raw.get("creationtime") is not None):
|
|
164
214
|
entry["Created At"] = entry_raw.get("creationtime")
|
|
165
215
|
|
|
@@ -652,27 +702,65 @@ class EntryManager:
|
|
|
652
702
|
def __get_digital_object_field_value(self, entry_raw, field):
|
|
653
703
|
"""Helper method to get digital object field value."""
|
|
654
704
|
digital_objects = entry_raw.get(_safe_lower(field.get('column')), None)
|
|
655
|
-
|
|
656
|
-
|
|
705
|
+
|
|
706
|
+
if digital_objects is None:
|
|
707
|
+
return None
|
|
657
708
|
|
|
658
709
|
# checks if its a valid json string
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
710
|
+
try:
|
|
711
|
+
data = json.loads(digital_objects) if isinstance(digital_objects, str) else digital_objects
|
|
712
|
+
except (TypeError, ValueError): # ValueError includes json.JSONDecodeError
|
|
713
|
+
return digital_objects
|
|
714
|
+
|
|
715
|
+
if isinstance(data, list):
|
|
716
|
+
return [_normalize_digital_object(obj) for obj in data if isinstance(obj, dict)]
|
|
717
|
+
|
|
718
|
+
def __attach_digital_objects(self, entry, entry_raw, field_items):
|
|
719
|
+
"""Make sure the digital objects of an entry are part of the result.
|
|
720
|
+
|
|
721
|
+
The backend returns digital objects under the *attribute id* of the
|
|
722
|
+
digital-object attribute (e.g. ``"6"``), and that column is not always
|
|
723
|
+
present in the entry-field metadata - so mapping fields alone silently
|
|
724
|
+
drops them. Scan the raw payload instead and expose whatever is there
|
|
725
|
+
under the digital-object field name (or ``DIGITAL_OBJECTS_KEY``).
|
|
726
|
+
"""
|
|
727
|
+
digital_objects = []
|
|
728
|
+
seen_ids = set()
|
|
729
|
+
|
|
730
|
+
for value in entry_raw.values():
|
|
731
|
+
objects = _parse_digital_objects(value)
|
|
732
|
+
|
|
733
|
+
if not objects:
|
|
734
|
+
continue
|
|
735
|
+
|
|
736
|
+
for obj in objects:
|
|
737
|
+
identifier = obj.get("Id")
|
|
738
|
+
if identifier is not None:
|
|
739
|
+
if identifier in seen_ids:
|
|
740
|
+
continue
|
|
741
|
+
seen_ids.add(identifier)
|
|
742
|
+
digital_objects.append(obj)
|
|
743
|
+
|
|
744
|
+
if not digital_objects:
|
|
745
|
+
return
|
|
746
|
+
|
|
747
|
+
target_key = DIGITAL_OBJECTS_KEY
|
|
748
|
+
|
|
749
|
+
for field in field_items:
|
|
750
|
+
if field.get('inputType') == DIGITAL_OBJECT_INPUT and field.get('displayName'):
|
|
751
|
+
target_key = field.get('displayName')
|
|
752
|
+
break
|
|
753
|
+
|
|
754
|
+
# A mapped field that already resolved to objects wins - the scan is
|
|
755
|
+
# only there to fill the gap when the metadata does not expose it.
|
|
756
|
+
existing = entry.get(target_key)
|
|
757
|
+
|
|
758
|
+
if isinstance(existing, list) and existing:
|
|
759
|
+
return
|
|
760
|
+
|
|
761
|
+
entry[target_key] = digital_objects
|
|
762
|
+
|
|
763
|
+
|
|
676
764
|
def __create_from_json_file(self, attribute: str, file_path: str):
|
|
677
765
|
"""Create a set of new entries from a file."""
|
|
678
766
|
|
|
@@ -3,9 +3,10 @@ from math import ceil
|
|
|
3
3
|
from os.path import exists
|
|
4
4
|
import json
|
|
5
5
|
from base64 import b64encode, b64decode
|
|
6
|
-
from das.common.api import post_data
|
|
6
|
+
from das.common.api import post_data, DEFAULT_TIMEOUT
|
|
7
7
|
from das.common.config import load_verify_ssl
|
|
8
|
-
from das.common.errors import extract_api_error
|
|
8
|
+
from das.common.errors import extract_api_error, build_api_error, connection_error
|
|
9
|
+
from das.common.exceptions import DasApiError
|
|
9
10
|
from das.services.service_base import ServiceBase
|
|
10
11
|
import uuid
|
|
11
12
|
import requests
|
|
@@ -122,6 +123,10 @@ class DigitalObjectsService(ServiceBase):
|
|
|
122
123
|
f"Upload failed for '{file_path}': no digital object returned on final chunk"
|
|
123
124
|
)
|
|
124
125
|
|
|
126
|
+
except DasApiError:
|
|
127
|
+
# Already a clear, categorised API error — let it propagate so
|
|
128
|
+
# callers can distinguish 4xx from 5xx (and keep the reference id).
|
|
129
|
+
raise
|
|
125
130
|
except Exception as e:
|
|
126
131
|
raise ValueError(f"Error uploading file '{file_path}': {str(e)}")
|
|
127
132
|
|
|
@@ -144,14 +149,52 @@ class DigitalObjectsService(ServiceBase):
|
|
|
144
149
|
}
|
|
145
150
|
|
|
146
151
|
try:
|
|
147
|
-
response = requests.post(
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
152
|
+
response = requests.post(
|
|
153
|
+
self.upload_digital_object_url,
|
|
154
|
+
headers=headers,
|
|
155
|
+
files=files,
|
|
156
|
+
verify=load_verify_ssl(),
|
|
157
|
+
timeout=DEFAULT_TIMEOUT,
|
|
158
|
+
)
|
|
153
159
|
except requests.RequestException as e:
|
|
154
|
-
|
|
160
|
+
# Transport-level failure (DNS/TLS/timeout/connection refused).
|
|
161
|
+
raise connection_error(e, self.upload_digital_object_url)
|
|
162
|
+
|
|
163
|
+
correlation_id = response.headers.get("X-Correlation-ID")
|
|
164
|
+
|
|
165
|
+
# Parse the JSON body regardless of status so we can surface the ABP
|
|
166
|
+
# envelope (message/details/validationErrors) instead of a raw dump.
|
|
167
|
+
try:
|
|
168
|
+
data = response.json()
|
|
169
|
+
except ValueError:
|
|
170
|
+
data = None
|
|
171
|
+
|
|
172
|
+
failed = response.status_code >= 400 or (
|
|
173
|
+
isinstance(data, dict) and data.get("success") is False
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
if failed:
|
|
177
|
+
if isinstance(data, dict):
|
|
178
|
+
data.setdefault("status_code", response.status_code)
|
|
179
|
+
if correlation_id:
|
|
180
|
+
data.setdefault("correlation_id", correlation_id)
|
|
181
|
+
raise build_api_error(data, default="File upload failed")
|
|
182
|
+
|
|
183
|
+
# Non-JSON error body (e.g. an HTML 500 page from a proxy).
|
|
184
|
+
raise build_api_error(
|
|
185
|
+
{
|
|
186
|
+
"error": (
|
|
187
|
+
f"The server returned HTTP {response.status_code} "
|
|
188
|
+
f"({response.reason}) during file upload."
|
|
189
|
+
),
|
|
190
|
+
"status_code": response.status_code,
|
|
191
|
+
"correlation_id": correlation_id,
|
|
192
|
+
"raw_content": (response.text or "")[:500],
|
|
193
|
+
},
|
|
194
|
+
default="File upload failed",
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
return data
|
|
155
198
|
|
|
156
199
|
def download_digital_object(self, output_path: str, digital_object_id: str = None, digital_object_code: str = None):
|
|
157
200
|
"""Download a digital object from the digital object service."""
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: das-cli
|
|
3
|
-
Version: 1.6.
|
|
3
|
+
Version: 1.6.6
|
|
4
4
|
Summary: DAS api client.
|
|
5
5
|
Author: Royal Netherlands Institute for Sea Research
|
|
6
6
|
License-Expression: MIT
|
|
@@ -362,6 +362,20 @@ entry = entries.get(id="6b0e68e6-00cd-43a7-9c51-d56c9c091123")
|
|
|
362
362
|
entry = entries.get_entry("6b0e68e6-00cd-43a7-9c51-d56c9c091123")
|
|
363
363
|
```
|
|
364
364
|
|
|
365
|
+
When the entry has digital objects attached they are always included, even for
|
|
366
|
+
attributes whose entry-field metadata does not expose a digital-object field.
|
|
367
|
+
They land under the digital-object field's display name when there is one, and
|
|
368
|
+
under `"Digital Object(s)"` otherwise:
|
|
369
|
+
|
|
370
|
+
```python
|
|
371
|
+
for obj in entry.get("Digital Object(s)", []):
|
|
372
|
+
print(obj["Id"], obj["Name"], obj["Type"], obj["Links"])
|
|
373
|
+
# 1715e27d-bc89-4f9c-8fdf-36ad2da333c6 zeynep.erdem.jpg Image 4d.b.cb
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
`das entry get` and `das search entry <id>` print the same objects as a block
|
|
377
|
+
below the field list (or inline in the payload with `--format json`).
|
|
378
|
+
|
|
365
379
|
#### `create` — create one or many entries
|
|
366
380
|
|
|
367
381
|
```python
|
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
"""Shared helpers for turning HTTP/API failures into clear, human-readable messages.
|
|
2
|
-
|
|
3
|
-
The goal is to never surface a raw stack trace or a raw Python dict/JSON blob to
|
|
4
|
-
the user. Instead we extract the message the API actually returned (ABP wraps it
|
|
5
|
-
in an ``error`` object) and add the HTTP status code when we have one.
|
|
6
|
-
"""
|
|
7
|
-
import requests
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
def describe_request_exception(exc: Exception, url: str = None) -> str:
|
|
11
|
-
"""Return a friendly message for a ``requests`` exception.
|
|
12
|
-
|
|
13
|
-
Distinguishes the common connection-level failures (bad/self-signed TLS
|
|
14
|
-
certificate, host unreachable, timeout) so the user gets an actionable hint
|
|
15
|
-
instead of an opaque traceback.
|
|
16
|
-
"""
|
|
17
|
-
where = f" ({url})" if url else ""
|
|
18
|
-
|
|
19
|
-
if isinstance(exc, requests.exceptions.SSLError):
|
|
20
|
-
return (
|
|
21
|
-
"SSL certificate verification failed for the server"
|
|
22
|
-
f"{where}. The host may be using a self-signed or otherwise "
|
|
23
|
-
"untrusted certificate. If you trust this host, disable "
|
|
24
|
-
"verification with 'das config ssl-verify false'. "
|
|
25
|
-
f"Details: {exc}"
|
|
26
|
-
)
|
|
27
|
-
if isinstance(exc, requests.exceptions.ConnectTimeout):
|
|
28
|
-
return f"Timed out while connecting to the server{where}. Details: {exc}"
|
|
29
|
-
if isinstance(exc, requests.exceptions.ReadTimeout):
|
|
30
|
-
return f"The server{where} took too long to respond. Details: {exc}"
|
|
31
|
-
if isinstance(exc, requests.exceptions.Timeout):
|
|
32
|
-
return f"The request timed out{where}. Details: {exc}"
|
|
33
|
-
if isinstance(exc, requests.exceptions.ConnectionError):
|
|
34
|
-
return (
|
|
35
|
-
f"Could not connect to the server{where}. Check that the API URL is "
|
|
36
|
-
"correct and that the host is reachable. "
|
|
37
|
-
f"Details: {exc}"
|
|
38
|
-
)
|
|
39
|
-
return str(exc)
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
def extract_api_error(response, default: str = "Unknown error occurred") -> str:
|
|
43
|
-
"""Extract a human-readable error message from a parsed API response.
|
|
44
|
-
|
|
45
|
-
Handles the ABP envelope (``{"error": {"message": ..., "details": ...,
|
|
46
|
-
"validationErrors": [...]}}``) as well as plain-string errors produced by
|
|
47
|
-
:mod:`das.common.api`. When a status code is available it is prefixed so the
|
|
48
|
-
caller can tell a 404 from a 500.
|
|
49
|
-
"""
|
|
50
|
-
if not isinstance(response, dict):
|
|
51
|
-
text = str(response).strip()
|
|
52
|
-
return text or default
|
|
53
|
-
|
|
54
|
-
status_code = response.get("status_code")
|
|
55
|
-
|
|
56
|
-
def _with_status(message: str) -> str:
|
|
57
|
-
message = (message or "").strip()
|
|
58
|
-
if status_code and message:
|
|
59
|
-
return f"HTTP {status_code}: {message}"
|
|
60
|
-
if status_code:
|
|
61
|
-
return f"HTTP {status_code}"
|
|
62
|
-
return message or default
|
|
63
|
-
|
|
64
|
-
error = response.get("error")
|
|
65
|
-
|
|
66
|
-
if isinstance(error, dict):
|
|
67
|
-
parts = []
|
|
68
|
-
message = (error.get("message") or "").strip()
|
|
69
|
-
details = (error.get("details") or "").strip()
|
|
70
|
-
if message:
|
|
71
|
-
parts.append(message)
|
|
72
|
-
if details and details != message:
|
|
73
|
-
parts.append(details)
|
|
74
|
-
|
|
75
|
-
validation_errors = error.get("validationErrors")
|
|
76
|
-
if isinstance(validation_errors, list):
|
|
77
|
-
for item in validation_errors:
|
|
78
|
-
if isinstance(item, dict) and item.get("message"):
|
|
79
|
-
parts.append(str(item["message"]).strip())
|
|
80
|
-
|
|
81
|
-
if parts:
|
|
82
|
-
return _with_status(" - ".join(parts))
|
|
83
|
-
return _with_status("")
|
|
84
|
-
|
|
85
|
-
if isinstance(error, str) and error.strip():
|
|
86
|
-
return _with_status(error)
|
|
87
|
-
|
|
88
|
-
# No structured error but the response still failed (e.g. non-JSON body).
|
|
89
|
-
raw = response.get("raw_content")
|
|
90
|
-
if raw:
|
|
91
|
-
return _with_status(str(raw))
|
|
92
|
-
|
|
93
|
-
return _with_status("")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|