das-cli 1.7.6__tar.gz → 1.8.0__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.7.6/das_cli.egg-info → das_cli-1.8.0}/PKG-INFO +28 -1
- {das_cli-1.7.6 → das_cli-1.8.0}/README.md +27 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/common/api.py +21 -5
- {das_cli-1.7.6 → das_cli-1.8.0}/das/common/config.py +43 -17
- {das_cli-1.7.6 → das_cli-1.8.0}/das/managers/entries_manager.py +158 -36
- {das_cli-1.7.6 → das_cli-1.8.0}/das/services/attributes.py +9 -1
- {das_cli-1.7.6 → das_cli-1.8.0}/das/services/entry_fields.py +17 -0
- {das_cli-1.7.6 → das_cli-1.8.0/das_cli.egg-info}/PKG-INFO +28 -1
- {das_cli-1.7.6 → das_cli-1.8.0}/pyproject.toml +1 -1
- {das_cli-1.7.6 → das_cli-1.8.0}/LICENSE +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/MANIFEST.in +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/__init__.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/ai/plugins/dasai.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/ai/plugins/entries/entries_plugin.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/app.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/authentication/auth.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/authentication/oauth.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/authentication/secure_input.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/cli.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/common/entry_fields_constants.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/common/enums.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/common/errors.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/common/exceptions.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/common/file_utils.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/managers/__init__.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/managers/digital_objects_manager.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/managers/download_manager.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/managers/search_manager.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/services/cache.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/services/das_elastic_search.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/services/digital_objects.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/services/downloads.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/services/entries.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/services/hangfire.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/services/search.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/services/service_base.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/services/session.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das/services/users.py +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das_cli.egg-info/SOURCES.txt +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das_cli.egg-info/dependency_links.txt +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das_cli.egg-info/entry_points.txt +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das_cli.egg-info/requires.txt +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/das_cli.egg-info/top_level.txt +0 -0
- {das_cli-1.7.6 → das_cli-1.8.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: das-cli
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.8.0
|
|
4
4
|
Summary: DAS api client.
|
|
5
5
|
Author: Royal Netherlands Institute for Sea Research
|
|
6
6
|
License-Expression: MIT
|
|
@@ -511,6 +511,11 @@ result = entries.create(attribute="Cores", entry={
|
|
|
511
511
|
# result -> [{"id": "<guid>", "code": "zb.b.xxx", "status": "success"}]
|
|
512
512
|
new_id = result[0]["id"]
|
|
513
513
|
|
|
514
|
+
# The code is generated by the server and read back with a second request.
|
|
515
|
+
# Skip that request when only the id is needed (imports, benchmarks):
|
|
516
|
+
result = entries.create(attribute="Cores", entry={...}, fetch_code=False)
|
|
517
|
+
# result -> [{"id": "<guid>", "status": "success"}]
|
|
518
|
+
|
|
514
519
|
# Bulk create
|
|
515
520
|
results = entries.create(attribute="Cores", entries=[
|
|
516
521
|
{"Alias": "bulk.001", "Event": "64PE428-02PC", "Number": 1},
|
|
@@ -529,6 +534,28 @@ entries.create(attribute="Cruise", entry={
|
|
|
529
534
|
})
|
|
530
535
|
```
|
|
531
536
|
|
|
537
|
+
#### `warm_select_cache` — pre-resolve select values before an import
|
|
538
|
+
|
|
539
|
+
Every select field value (`"Event": "64PE428-02PC"`, `"Device": "CTD"`) is
|
|
540
|
+
resolved with one search request the first time the manager sees it. An
|
|
541
|
+
import that references many different stations, devices or cruises pays one
|
|
542
|
+
request per distinct value. `warm_select_cache` loads the options of every
|
|
543
|
+
select field of an attribute up front and caches them by code, display name
|
|
544
|
+
and id, so the rows that follow resolve without a request:
|
|
545
|
+
|
|
546
|
+
```python
|
|
547
|
+
entries = EntryManager()
|
|
548
|
+
cached = entries.warm_select_cache("Event") # one request per select field (per 1000 options)
|
|
549
|
+
print(f"{cached} select options cached")
|
|
550
|
+
|
|
551
|
+
for row in rows:
|
|
552
|
+
entries.create(attribute="Event", entry=row, fetch_code=False) # one request per row
|
|
553
|
+
```
|
|
554
|
+
|
|
555
|
+
Values must match the server's spelling and case; anything else still falls
|
|
556
|
+
back to a search. Fields with more than `max_results` options (default 1000)
|
|
557
|
+
are warmed partially. The cache lives as long as the manager instance.
|
|
558
|
+
|
|
532
559
|
#### `update` — update one or many entries
|
|
533
560
|
|
|
534
561
|
```python
|
|
@@ -488,6 +488,11 @@ result = entries.create(attribute="Cores", entry={
|
|
|
488
488
|
# result -> [{"id": "<guid>", "code": "zb.b.xxx", "status": "success"}]
|
|
489
489
|
new_id = result[0]["id"]
|
|
490
490
|
|
|
491
|
+
# The code is generated by the server and read back with a second request.
|
|
492
|
+
# Skip that request when only the id is needed (imports, benchmarks):
|
|
493
|
+
result = entries.create(attribute="Cores", entry={...}, fetch_code=False)
|
|
494
|
+
# result -> [{"id": "<guid>", "status": "success"}]
|
|
495
|
+
|
|
491
496
|
# Bulk create
|
|
492
497
|
results = entries.create(attribute="Cores", entries=[
|
|
493
498
|
{"Alias": "bulk.001", "Event": "64PE428-02PC", "Number": 1},
|
|
@@ -506,6 +511,28 @@ entries.create(attribute="Cruise", entry={
|
|
|
506
511
|
})
|
|
507
512
|
```
|
|
508
513
|
|
|
514
|
+
#### `warm_select_cache` — pre-resolve select values before an import
|
|
515
|
+
|
|
516
|
+
Every select field value (`"Event": "64PE428-02PC"`, `"Device": "CTD"`) is
|
|
517
|
+
resolved with one search request the first time the manager sees it. An
|
|
518
|
+
import that references many different stations, devices or cruises pays one
|
|
519
|
+
request per distinct value. `warm_select_cache` loads the options of every
|
|
520
|
+
select field of an attribute up front and caches them by code, display name
|
|
521
|
+
and id, so the rows that follow resolve without a request:
|
|
522
|
+
|
|
523
|
+
```python
|
|
524
|
+
entries = EntryManager()
|
|
525
|
+
cached = entries.warm_select_cache("Event") # one request per select field (per 1000 options)
|
|
526
|
+
print(f"{cached} select options cached")
|
|
527
|
+
|
|
528
|
+
for row in rows:
|
|
529
|
+
entries.create(attribute="Event", entry=row, fetch_code=False) # one request per row
|
|
530
|
+
```
|
|
531
|
+
|
|
532
|
+
Values must match the server's spelling and case; anything else still falls
|
|
533
|
+
back to a search. Fields with more than `max_results` options (default 1000)
|
|
534
|
+
are warmed partially. The cache lives as long as the manager instance.
|
|
535
|
+
|
|
509
536
|
#### `update` — update one or many entries
|
|
510
537
|
|
|
511
538
|
```python
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import json
|
|
2
2
|
import logging
|
|
3
|
+
import threading
|
|
3
4
|
import requests
|
|
4
5
|
from das.common.config import load_verify_ssl
|
|
5
6
|
from das.common.errors import describe_request_exception
|
|
@@ -10,6 +11,21 @@ logger = logging.getLogger("das")
|
|
|
10
11
|
# hanging indefinitely on an unreachable host.
|
|
11
12
|
DEFAULT_TIMEOUT = (10, 60)
|
|
12
13
|
|
|
14
|
+
# One ``requests.Session`` per thread. A session keeps the TCP/TLS connection
|
|
15
|
+
# to the API alive between calls (HTTP keep-alive); without it every request
|
|
16
|
+
# pays a fresh DNS lookup, TCP connect and TLS handshake, which dominates the
|
|
17
|
+
# cost of the many small calls an entry import makes. ``requests.Session`` is
|
|
18
|
+
# not guaranteed thread-safe, hence thread-local.
|
|
19
|
+
_local = threading.local()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _get_session() -> requests.Session:
|
|
23
|
+
session = getattr(_local, "session", None)
|
|
24
|
+
if session is None:
|
|
25
|
+
session = requests.Session()
|
|
26
|
+
_local.session = session
|
|
27
|
+
return session
|
|
28
|
+
|
|
13
29
|
|
|
14
30
|
def _process_response(response, action: str):
|
|
15
31
|
"""Turn a ``requests.Response`` into a parsed dict or a structured error dict.
|
|
@@ -85,7 +101,7 @@ def get_data(url, headers=None, params=None):
|
|
|
85
101
|
"""
|
|
86
102
|
logger.debug("GET %s", url)
|
|
87
103
|
try:
|
|
88
|
-
response =
|
|
104
|
+
response = _get_session().get(
|
|
89
105
|
url, headers=headers, params=params,
|
|
90
106
|
verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
|
|
91
107
|
)
|
|
@@ -104,7 +120,7 @@ def get_binary_response(url, headers=None, params=None, stream=True):
|
|
|
104
120
|
"""
|
|
105
121
|
logger.debug("GET (binary) %s", url)
|
|
106
122
|
try:
|
|
107
|
-
response =
|
|
123
|
+
response = _get_session().get(
|
|
108
124
|
url,
|
|
109
125
|
headers=headers,
|
|
110
126
|
params=params,
|
|
@@ -133,7 +149,7 @@ def post_data(url, headers=None, data=None):
|
|
|
133
149
|
"""
|
|
134
150
|
logger.debug("POST %s", url)
|
|
135
151
|
try:
|
|
136
|
-
response =
|
|
152
|
+
response = _get_session().post(
|
|
137
153
|
url, headers=headers, json=data,
|
|
138
154
|
verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
|
|
139
155
|
)
|
|
@@ -157,7 +173,7 @@ def put_data(url, headers=None, data=None):
|
|
|
157
173
|
"""
|
|
158
174
|
logger.debug("PUT %s", url)
|
|
159
175
|
try:
|
|
160
|
-
response =
|
|
176
|
+
response = _get_session().put(
|
|
161
177
|
url, headers=headers, json=data,
|
|
162
178
|
verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
|
|
163
179
|
)
|
|
@@ -181,7 +197,7 @@ def delete_data(url, headers=None, data=None):
|
|
|
181
197
|
"""
|
|
182
198
|
logger.debug("DELETE %s", url)
|
|
183
199
|
try:
|
|
184
|
-
response =
|
|
200
|
+
response = _get_session().delete(
|
|
185
201
|
url, headers=headers, json=data,
|
|
186
202
|
verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
|
|
187
203
|
)
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import copy
|
|
1
2
|
import json
|
|
2
3
|
import os
|
|
3
4
|
import time
|
|
@@ -48,6 +49,7 @@ logging.basicConfig(
|
|
|
48
49
|
SERVICE_NAME = "Data-Archive-System"
|
|
49
50
|
DEFAULT_BASE_URL = "https://localhost:44301" # ← change to your API
|
|
50
51
|
VERIFY_SSL = True # Default is True for secure connections
|
|
52
|
+
_ssl_warning_shown = False
|
|
51
53
|
TOKEN_FIELD = "accessToken"
|
|
52
54
|
# Environment variable (usually set in .env) holding a DAS API key. It takes
|
|
53
55
|
# precedence over any credential saved by 'das login'.
|
|
@@ -64,6 +66,22 @@ def _config_dir() -> Path:
|
|
|
64
66
|
|
|
65
67
|
CONFIG_FILE = _config_dir() / "config.json"
|
|
66
68
|
|
|
69
|
+
# Parsed config.json, keyed on the file's path and stat signature. Settings
|
|
70
|
+
# such as verify_ssl and auth_type are consulted on every API request, so
|
|
71
|
+
# re-reading and re-parsing the file each time is wasted work. Any write
|
|
72
|
+
# changes the mtime/size, which invalidates the cache.
|
|
73
|
+
_config_cache = {"key": None, "data": None}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _read_config() -> dict:
|
|
77
|
+
"""Return a fresh copy of the parsed config file (raises like json.loads)."""
|
|
78
|
+
stat = CONFIG_FILE.stat()
|
|
79
|
+
key = (str(CONFIG_FILE), stat.st_mtime_ns, stat.st_size)
|
|
80
|
+
if _config_cache["key"] != key:
|
|
81
|
+
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
|
82
|
+
_config_cache["key"], _config_cache["data"] = key, data
|
|
83
|
+
return copy.deepcopy(_config_cache["data"])
|
|
84
|
+
|
|
67
85
|
def normalize_api_url(api_url: Optional[str]) -> Optional[str]:
|
|
68
86
|
"""Strip whitespace and trailing slashes. Services append "/api/...", and a
|
|
69
87
|
"//api/..." URL makes the backend answer HTTP 200 with a non-JSON body."""
|
|
@@ -75,7 +93,7 @@ def save_api_url(api_url: str) -> None:
|
|
|
75
93
|
config = {}
|
|
76
94
|
if CONFIG_FILE.exists():
|
|
77
95
|
try:
|
|
78
|
-
config =
|
|
96
|
+
config = _read_config()
|
|
79
97
|
except Exception:
|
|
80
98
|
config = {}
|
|
81
99
|
config["api_url"] = normalize_api_url(api_url)
|
|
@@ -87,7 +105,7 @@ def load_api_url() -> Optional[str]:
|
|
|
87
105
|
return env_url
|
|
88
106
|
if CONFIG_FILE.exists():
|
|
89
107
|
try:
|
|
90
|
-
return normalize_api_url(
|
|
108
|
+
return normalize_api_url(_read_config().get("api_url"))
|
|
91
109
|
except Exception:
|
|
92
110
|
return None
|
|
93
111
|
return None
|
|
@@ -103,7 +121,7 @@ def save_verify_ssl(verify: bool) -> None:
|
|
|
103
121
|
config = {}
|
|
104
122
|
if CONFIG_FILE.exists():
|
|
105
123
|
try:
|
|
106
|
-
config =
|
|
124
|
+
config = _read_config()
|
|
107
125
|
except Exception:
|
|
108
126
|
config = {}
|
|
109
127
|
config["verify_ssl"] = verify
|
|
@@ -112,6 +130,14 @@ def save_verify_ssl(verify: bool) -> None:
|
|
|
112
130
|
VERIFY_SSL = verify
|
|
113
131
|
CONFIG_FILE.write_text(json.dumps(config), encoding="utf-8")
|
|
114
132
|
|
|
133
|
+
def _warn_ssl_disabled() -> None:
|
|
134
|
+
"""Tell the user once per process (not once per request) that SSL is off."""
|
|
135
|
+
global _ssl_warning_shown
|
|
136
|
+
if not _ssl_warning_shown:
|
|
137
|
+
_ssl_warning_shown = True
|
|
138
|
+
print("SSL certificate verification is disabled")
|
|
139
|
+
|
|
140
|
+
|
|
115
141
|
def load_verify_ssl() -> bool:
|
|
116
142
|
"""
|
|
117
143
|
Load the VERIFY_SSL setting from the config file.
|
|
@@ -122,27 +148,27 @@ def load_verify_ssl() -> bool:
|
|
|
122
148
|
global VERIFY_SSL
|
|
123
149
|
if CONFIG_FILE.exists():
|
|
124
150
|
try:
|
|
125
|
-
config =
|
|
151
|
+
config = _read_config()
|
|
126
152
|
|
|
127
153
|
verify = config.get("verify_ssl")
|
|
128
154
|
verify_explicit = config.get("verify_ssl_explicit", False)
|
|
129
155
|
if verify is not None and verify_explicit:
|
|
130
156
|
VERIFY_SSL = verify
|
|
131
157
|
if not VERIFY_SSL:
|
|
132
|
-
|
|
158
|
+
_warn_ssl_disabled()
|
|
133
159
|
return verify
|
|
134
160
|
|
|
135
161
|
env_verify_ssl = os.getenv("VERIFY_SSL")
|
|
136
162
|
if env_verify_ssl is not None:
|
|
137
163
|
VERIFY_SSL = env_verify_ssl.strip().lower() == "true"
|
|
138
164
|
if not VERIFY_SSL:
|
|
139
|
-
|
|
165
|
+
_warn_ssl_disabled()
|
|
140
166
|
return VERIFY_SSL
|
|
141
167
|
|
|
142
168
|
if verify is not None:
|
|
143
169
|
VERIFY_SSL = verify
|
|
144
170
|
if not VERIFY_SSL:
|
|
145
|
-
|
|
171
|
+
_warn_ssl_disabled()
|
|
146
172
|
return verify
|
|
147
173
|
|
|
148
174
|
raise ValueError("SSL certificate verification is not set")
|
|
@@ -160,7 +186,7 @@ def save_log_level(level) -> None:
|
|
|
160
186
|
config = {}
|
|
161
187
|
if CONFIG_FILE.exists():
|
|
162
188
|
try:
|
|
163
|
-
config =
|
|
189
|
+
config = _read_config()
|
|
164
190
|
except Exception:
|
|
165
191
|
config = {}
|
|
166
192
|
config["log_level"] = level.name
|
|
@@ -204,7 +230,7 @@ def load_log_level() -> LogLevel:
|
|
|
204
230
|
pass
|
|
205
231
|
if CONFIG_FILE.exists():
|
|
206
232
|
try:
|
|
207
|
-
stored =
|
|
233
|
+
stored = _read_config().get("log_level")
|
|
208
234
|
if stored:
|
|
209
235
|
return parse_log_level(stored)
|
|
210
236
|
except Exception:
|
|
@@ -221,7 +247,7 @@ def save_log_file(path) -> None:
|
|
|
221
247
|
config = {}
|
|
222
248
|
if CONFIG_FILE.exists():
|
|
223
249
|
try:
|
|
224
|
-
config =
|
|
250
|
+
config = _read_config()
|
|
225
251
|
except Exception:
|
|
226
252
|
config = {}
|
|
227
253
|
if path:
|
|
@@ -238,7 +264,7 @@ def load_log_file() -> Optional[str]:
|
|
|
238
264
|
return env_path
|
|
239
265
|
if CONFIG_FILE.exists():
|
|
240
266
|
try:
|
|
241
|
-
return
|
|
267
|
+
return _read_config().get("log_file")
|
|
242
268
|
except Exception:
|
|
243
269
|
return None
|
|
244
270
|
return None
|
|
@@ -504,7 +530,7 @@ def save_oauth_config(client_id: str, authority: str, scope: str) -> None:
|
|
|
504
530
|
config = {}
|
|
505
531
|
if CONFIG_FILE.exists():
|
|
506
532
|
try:
|
|
507
|
-
config =
|
|
533
|
+
config = _read_config()
|
|
508
534
|
except Exception:
|
|
509
535
|
config = {}
|
|
510
536
|
config.setdefault("oauth", {})
|
|
@@ -518,7 +544,7 @@ def load_oauth_config() -> dict:
|
|
|
518
544
|
"""Return the stored OAuth config dict (may be empty if not configured)."""
|
|
519
545
|
if CONFIG_FILE.exists():
|
|
520
546
|
try:
|
|
521
|
-
return
|
|
547
|
+
return _read_config().get("oauth", {})
|
|
522
548
|
except Exception:
|
|
523
549
|
pass
|
|
524
550
|
return {}
|
|
@@ -530,7 +556,7 @@ def get_auth_type() -> str:
|
|
|
530
556
|
return "api_key"
|
|
531
557
|
if CONFIG_FILE.exists():
|
|
532
558
|
try:
|
|
533
|
-
return
|
|
559
|
+
return _read_config().get("auth_type", "basic")
|
|
534
560
|
except Exception:
|
|
535
561
|
pass
|
|
536
562
|
return "basic"
|
|
@@ -541,7 +567,7 @@ def set_auth_type(auth_type: str) -> None:
|
|
|
541
567
|
config = {}
|
|
542
568
|
if CONFIG_FILE.exists():
|
|
543
569
|
try:
|
|
544
|
-
config =
|
|
570
|
+
config = _read_config()
|
|
545
571
|
except Exception:
|
|
546
572
|
config = {}
|
|
547
573
|
config["auth_type"] = auth_type
|
|
@@ -553,7 +579,7 @@ def save_token_expiry(expires_at: float) -> None:
|
|
|
553
579
|
config = {}
|
|
554
580
|
if CONFIG_FILE.exists():
|
|
555
581
|
try:
|
|
556
|
-
config =
|
|
582
|
+
config = _read_config()
|
|
557
583
|
except Exception:
|
|
558
584
|
config = {}
|
|
559
585
|
config.setdefault("oauth", {})
|
|
@@ -565,7 +591,7 @@ def load_token_expiry() -> Optional[float]:
|
|
|
565
591
|
"""Return the stored token expiry timestamp, or None."""
|
|
566
592
|
if CONFIG_FILE.exists():
|
|
567
593
|
try:
|
|
568
|
-
cfg =
|
|
594
|
+
cfg = _read_config()
|
|
569
595
|
return cfg.get("oauth", {}).get("token_expires_at")
|
|
570
596
|
except Exception:
|
|
571
597
|
pass
|
|
@@ -131,6 +131,11 @@ class EntryManager:
|
|
|
131
131
|
self.attribute_service = AttributesService(base_url)
|
|
132
132
|
self.user_service = UsersService(base_url)
|
|
133
133
|
self.das_elastic_search = DasElasticSearch(base_url)
|
|
134
|
+
# Resolved select/lookup values: (attribute_id, query, max) -> JSON
|
|
135
|
+
# string. Bulk imports reference the same Cruise/Device/etc. on every
|
|
136
|
+
# row; resolve each one once per manager. Only hits are cached, so a
|
|
137
|
+
# value that does not exist yet is looked up again next time.
|
|
138
|
+
self._select_value_cache = {}
|
|
134
139
|
|
|
135
140
|
def delete(self, id: str = None, code: str = None) -> bool:
|
|
136
141
|
"""Delete an entry by its id or code."""
|
|
@@ -243,7 +248,7 @@ class EntryManager:
|
|
|
243
248
|
except Exception as e:
|
|
244
249
|
raise ValueError(f"Error processing entry data: {e}")
|
|
245
250
|
|
|
246
|
-
def create(self, attribute: str, entry: dict = None, entries: list = None) -> list:
|
|
251
|
+
def create(self, attribute: str, entry: dict = None, entries: list = None, fetch_code: bool = True) -> list:
|
|
247
252
|
"""
|
|
248
253
|
Create one or more new entries.
|
|
249
254
|
|
|
@@ -251,6 +256,11 @@ class EntryManager:
|
|
|
251
256
|
attribute (str): The attribute name
|
|
252
257
|
entry (dict, optional): Single entry data
|
|
253
258
|
entries (list, optional): List of entry data for creating multiple entries
|
|
259
|
+
fetch_code (bool, optional): For a single ``entry``, also read the
|
|
260
|
+
new entry back to report its server-generated ``code``. That is
|
|
261
|
+
a second request per entry; pass ``False`` when only the id is
|
|
262
|
+
needed (e.g. imports). Ignored for ``entries``, which never
|
|
263
|
+
reports codes.
|
|
254
264
|
|
|
255
265
|
Returns:
|
|
256
266
|
list: List of created entry IDs with status information
|
|
@@ -285,7 +295,9 @@ class EntryManager:
|
|
|
285
295
|
elif entry is not None:
|
|
286
296
|
# Single entry creation
|
|
287
297
|
result = self._create_single_entry(attribute, entry)
|
|
288
|
-
|
|
298
|
+
if not fetch_code:
|
|
299
|
+
return [{"id": result, "status": "success"}]
|
|
300
|
+
# The server generates the code; Create only returns the id.
|
|
289
301
|
new_entry_code = self.entry_service.get(id=result).get('entry').get('code')
|
|
290
302
|
return [{"id": result, "code": new_entry_code, "status": "success"}]
|
|
291
303
|
|
|
@@ -608,7 +620,44 @@ class EntryManager:
|
|
|
608
620
|
# Scalars (ints/floats/bools from files) need to be strings to query.
|
|
609
621
|
source = _coerce_to_str(source)
|
|
610
622
|
|
|
623
|
+
attribute_id, is_multiselect = self.__parse_select_field(field)
|
|
624
|
+
|
|
625
|
+
expected_max_result_count = 1
|
|
626
|
+
if is_multiselect:
|
|
627
|
+
expected_max_result_count = len(source.split(','))
|
|
628
|
+
|
|
629
|
+
search_params = {
|
|
630
|
+
"attributeId": attribute_id,
|
|
631
|
+
"queryString": self.__get_query_string(source, is_multiselect),
|
|
632
|
+
"maxResultCount": expected_max_result_count,
|
|
633
|
+
"skipCount": 0
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
cache_key = (attribute_id, search_params["queryString"], expected_max_result_count)
|
|
637
|
+
if cache_key in self._select_value_cache:
|
|
638
|
+
return self._select_value_cache[cache_key]
|
|
639
|
+
|
|
640
|
+
search_response = self.search_service.search_entries(**search_params)
|
|
641
|
+
|
|
642
|
+
if search_response.get('totalCount', 0) == 0:
|
|
643
|
+
raise ValueError(f"No results found for {field.get('displayName')}: {source}. Attribute ID: {attribute_id}")
|
|
644
|
+
if search_response and 'items' in search_response and len(search_response['items']) > 0:
|
|
645
|
+
result_list = [self.__select_item_to_result(item, attribute_id) for item in search_response['items']]
|
|
646
|
+
value = json.dumps(result_list)
|
|
647
|
+
self._select_value_cache[cache_key] = value
|
|
648
|
+
return value
|
|
649
|
+
else:
|
|
650
|
+
return source
|
|
651
|
+
|
|
652
|
+
def __parse_select_field(self, field) -> tuple:
|
|
653
|
+
"""Return ``(datasource attribute id, is_multiselect)`` of a select field.
|
|
654
|
+
|
|
655
|
+
The attribute the options come from is declared in the field's custom
|
|
656
|
+
data (``datasource.attributeId``); older fields encode it in the column
|
|
657
|
+
name (``x27`` / ``27``). ``-1`` when neither is present.
|
|
658
|
+
"""
|
|
611
659
|
attribute_id = -1
|
|
660
|
+
is_multiselect = False
|
|
612
661
|
|
|
613
662
|
# convert all keys to lowercase
|
|
614
663
|
field = {str(k).lower(): v for k, v in field.items()}
|
|
@@ -620,9 +669,6 @@ class EntryManager:
|
|
|
620
669
|
elif len(column) >= 2 and column[0].isalpha() and column[1:].isdigit():
|
|
621
670
|
attribute_id = int(column[1:])
|
|
622
671
|
|
|
623
|
-
customdata = None
|
|
624
|
-
is_multiselect = False
|
|
625
|
-
|
|
626
672
|
if not field.get('customdata', None) is None and field.get('customdata') != "":
|
|
627
673
|
try:
|
|
628
674
|
customdata_string = field.get('customdata').lower()
|
|
@@ -637,36 +683,112 @@ class EntryManager:
|
|
|
637
683
|
except json.JSONDecodeError:
|
|
638
684
|
raise ValueError(f"Invalid customdata JSON: {field.get('customdata')}")
|
|
639
685
|
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
686
|
+
return attribute_id, bool(is_multiselect)
|
|
687
|
+
|
|
688
|
+
@staticmethod
|
|
689
|
+
def __select_item_to_result(item: dict, attribute_id) -> dict:
|
|
690
|
+
"""Shape one search hit the way the server expects a select value."""
|
|
691
|
+
entry = item.get('entry', {}) or {}
|
|
692
|
+
result = {
|
|
693
|
+
'id': entry.get('id'),
|
|
694
|
+
'name': entry.get('displayname'),
|
|
695
|
+
'code': entry.get('code'),
|
|
696
|
+
'alias': entry.get('alias', None),
|
|
697
|
+
'acronym': entry.get('acronym', None),
|
|
698
|
+
'attributeid': attribute_id,
|
|
649
699
|
}
|
|
650
|
-
|
|
651
|
-
search_response = self.search_service.search_entries(**search_params)
|
|
700
|
+
return {k: v for k, v in result.items() if v is not None}
|
|
652
701
|
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
702
|
+
def __iter_select_fields(self, fields: list):
|
|
703
|
+
"""Yield every select field of an attribute, including those nested in a group box."""
|
|
704
|
+
for field in fields:
|
|
705
|
+
if field.get('inputType') == GROUP_BOX_INPUT:
|
|
706
|
+
custom_data = field.get('customData', None)
|
|
707
|
+
if custom_data is None:
|
|
708
|
+
continue
|
|
709
|
+
try:
|
|
710
|
+
nested = json.loads(custom_data).get('fields') or []
|
|
711
|
+
except (json.JSONDecodeError, AttributeError):
|
|
712
|
+
continue
|
|
713
|
+
for nested_field in nested:
|
|
714
|
+
if isinstance(nested_field, dict) and nested_field.get('inputType') == SELECT_COMBO_INPUT:
|
|
715
|
+
yield nested_field
|
|
716
|
+
elif field.get('inputType') == SELECT_COMBO_INPUT:
|
|
717
|
+
yield field
|
|
718
|
+
|
|
719
|
+
def warm_select_cache(self, attribute: str, max_results: int = 1000, page_size: int = 1000) -> int:
|
|
720
|
+
"""Pre-resolve the options of every select field of an attribute.
|
|
721
|
+
|
|
722
|
+
Resolving a select value (``"Device": "CTD"``) normally costs one
|
|
723
|
+
search request the first time each value is seen. For an import that
|
|
724
|
+
references many different stations, devices, cruises, etc. that is one
|
|
725
|
+
request per distinct value. This loads the options of each select
|
|
726
|
+
field up front (one request per page of ``page_size`` options) and
|
|
727
|
+
caches them under their code, display name and id, so later
|
|
728
|
+
``create``/``update`` calls resolve those values without a request.
|
|
729
|
+
|
|
730
|
+
Values must be given exactly as the server returns them (same case);
|
|
731
|
+
anything else still falls back to a search, as before. The cache
|
|
732
|
+
lives as long as this manager.
|
|
733
|
+
|
|
734
|
+
Args:
|
|
735
|
+
attribute (str): The attribute whose select fields to warm.
|
|
736
|
+
max_results (int, optional): Options to load per select field.
|
|
737
|
+
Fields with more options than this are warmed partially.
|
|
738
|
+
page_size (int, optional): Options per search request.
|
|
739
|
+
|
|
740
|
+
Returns:
|
|
741
|
+
int: Number of options cached.
|
|
742
|
+
"""
|
|
743
|
+
if not attribute:
|
|
744
|
+
raise ValueError("Attribute name is required")
|
|
745
|
+
if max_results <= 0 or page_size <= 0:
|
|
746
|
+
raise ValueError("max_results and page_size must be positive")
|
|
747
|
+
|
|
748
|
+
attribute_id = self.attribute_service.get_id(name=attribute)
|
|
749
|
+
entry_fields_response = self.entry_fields_service.get_entry_fields(attribute_id=attribute_id)
|
|
750
|
+
fields = entry_fields_response.get("result", {}).get("items", [])
|
|
751
|
+
|
|
752
|
+
warmed = 0
|
|
753
|
+
seen_sources = set()
|
|
754
|
+
|
|
755
|
+
for field in self.__iter_select_fields(fields):
|
|
756
|
+
source_attribute_id, is_multiselect = self.__parse_select_field(field)
|
|
757
|
+
if source_attribute_id is None or int(source_attribute_id) < 0 or source_attribute_id in seen_sources:
|
|
758
|
+
continue
|
|
759
|
+
seen_sources.add(source_attribute_id)
|
|
760
|
+
|
|
761
|
+
skip = 0
|
|
762
|
+
while skip < max_results:
|
|
763
|
+
response = self.search_service.search_entries(
|
|
764
|
+
attributeId=source_attribute_id,
|
|
765
|
+
queryString="",
|
|
766
|
+
maxResultCount=min(page_size, max_results - skip),
|
|
767
|
+
skipCount=skip,
|
|
768
|
+
)
|
|
769
|
+
items = (response or {}).get('items') or []
|
|
770
|
+
if not items:
|
|
771
|
+
break
|
|
772
|
+
|
|
773
|
+
for item in items:
|
|
774
|
+
result = self.__select_item_to_result(item, source_attribute_id)
|
|
775
|
+
value = json.dumps([result])
|
|
776
|
+
for key in (result.get('code'), result.get('name'), result.get('id')):
|
|
777
|
+
if _is_empty(key):
|
|
778
|
+
continue
|
|
779
|
+
key = _coerce_to_str(key)
|
|
780
|
+
# A field is either single- or multi-select; a one-value
|
|
781
|
+
# multiselect uses a different query string, so cache
|
|
782
|
+
# the one this field will actually ask for.
|
|
783
|
+
query = self.__get_query_string(key, is_multiselect)
|
|
784
|
+
self._select_value_cache[(source_attribute_id, query, 1)] = value
|
|
785
|
+
warmed += 1
|
|
786
|
+
|
|
787
|
+
skip += len(items)
|
|
788
|
+
if skip >= (response.get('totalCount') or 0):
|
|
789
|
+
break
|
|
790
|
+
|
|
791
|
+
return warmed
|
|
670
792
|
|
|
671
793
|
def __get_query_string(self, source: str, is_multiselect: bool) -> str:
|
|
672
794
|
|
|
@@ -828,7 +950,7 @@ class EntryManager:
|
|
|
828
950
|
for entry in entries:
|
|
829
951
|
if not isinstance(entry, dict):
|
|
830
952
|
raise ValueError("Each entry must be a dictionary")
|
|
831
|
-
self.create(attribute=attribute, entry=entry)
|
|
953
|
+
self.create(attribute=attribute, entry=entry, fetch_code=False)
|
|
832
954
|
|
|
833
955
|
def __create_from_csv_file(self, attribute: str, file_path: str):
|
|
834
956
|
"""Create a set of new entries from a file."""
|
|
@@ -840,7 +962,7 @@ class EntryManager:
|
|
|
840
962
|
entries = [row for row in reader]
|
|
841
963
|
|
|
842
964
|
for entry in entries:
|
|
843
|
-
self.create(attribute=attribute, entry=entry)
|
|
965
|
+
self.create(attribute=attribute, entry=entry, fetch_code=False)
|
|
844
966
|
|
|
845
967
|
|
|
846
968
|
def __create_from_excel_file(self, attribute: str, file_path: str):
|
|
@@ -855,7 +977,7 @@ class EntryManager:
|
|
|
855
977
|
entries = df.to_dict(orient='records')
|
|
856
978
|
|
|
857
979
|
for entry in entries:
|
|
858
|
-
self.create(attribute=attribute, entry=entry)
|
|
980
|
+
self.create(attribute=attribute, entry=entry, fetch_code=False)
|
|
859
981
|
|
|
860
982
|
|
|
861
983
|
def create_from_file(self, attribute: str, file_path: str):
|
|
@@ -7,6 +7,9 @@ class AttributesService(ServiceBase):
|
|
|
7
7
|
|
|
8
8
|
def __init__(self, base_url):
|
|
9
9
|
self.base_url = f"{base_url}/api/services/app/Attribute"
|
|
10
|
+
# name -> id. Attribute ids never change, and importers resolve the
|
|
11
|
+
# same attribute name for every row they create.
|
|
12
|
+
self._id_cache = {}
|
|
10
13
|
|
|
11
14
|
def get_attribute(self, id: int = None, name: str = None, alias: str = None, table_name: str = None):
|
|
12
15
|
if (id is None and name is None and alias is None and table_name is None):
|
|
@@ -45,11 +48,16 @@ class AttributesService(ServiceBase):
|
|
|
45
48
|
if (name is None):
|
|
46
49
|
raise ValueError("Name parameter must be provided")
|
|
47
50
|
|
|
51
|
+
if name in self._id_cache:
|
|
52
|
+
return self._id_cache[name]
|
|
53
|
+
|
|
48
54
|
url = f"{self.base_url}/GetAll?name={name}"
|
|
49
55
|
|
|
50
56
|
response = get_data(url, headers=self.set_auth_headers())
|
|
51
57
|
|
|
52
58
|
if response.get('success') == True:
|
|
53
|
-
|
|
59
|
+
attribute_id = response.get('result').get('items')[0].get('id')
|
|
60
|
+
self._id_cache[name] = attribute_id
|
|
61
|
+
return attribute_id
|
|
54
62
|
else:
|
|
55
63
|
raise ValueError(extract_api_error(response))
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
|
|
1
3
|
from das.common.api import get_data
|
|
2
4
|
from das.common.errors import extract_api_error
|
|
3
5
|
from das.services.service_base import ServiceBase
|
|
@@ -6,16 +8,31 @@ from das.services.service_base import ServiceBase
|
|
|
6
8
|
class EntryFieldsService(ServiceBase):
|
|
7
9
|
def __init__(self, base_url):
|
|
8
10
|
self.base_url = f"{base_url}/api/services/app/EntryField"
|
|
11
|
+
# (attribute_id, display_type) -> successful response. Field
|
|
12
|
+
# definitions are schema, not data: every get/create/update of an
|
|
13
|
+
# entry needs them, and they are identical for every entry of the
|
|
14
|
+
# attribute. Lives as long as this service instance; call
|
|
15
|
+
# clear_cache() if the schema changes while it is in use.
|
|
16
|
+
self._cache = {}
|
|
17
|
+
|
|
18
|
+
def clear_cache(self):
|
|
19
|
+
self._cache.clear()
|
|
9
20
|
|
|
10
21
|
def get_entry_fields(self, attribute_id: int, display_type: int = 2):
|
|
11
22
|
if (attribute_id is None):
|
|
12
23
|
raise ValueError("Attribute ID parameter must be provided")
|
|
13
24
|
|
|
25
|
+
key = (str(attribute_id), display_type)
|
|
26
|
+
if key in self._cache:
|
|
27
|
+
# Callers may modify the result; hand out a copy.
|
|
28
|
+
return copy.deepcopy(self._cache[key])
|
|
29
|
+
|
|
14
30
|
url = f"{self.base_url}/GetAll?AttributeId={attribute_id}&DisplayType={display_type}"
|
|
15
31
|
|
|
16
32
|
response = get_data(url, headers=self.set_auth_headers())
|
|
17
33
|
|
|
18
34
|
if response.get('success') == True:
|
|
35
|
+
self._cache[key] = copy.deepcopy(response)
|
|
19
36
|
return response
|
|
20
37
|
else:
|
|
21
38
|
raise ValueError(extract_api_error(response, "Unknown error in entry fields request"))
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: das-cli
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.8.0
|
|
4
4
|
Summary: DAS api client.
|
|
5
5
|
Author: Royal Netherlands Institute for Sea Research
|
|
6
6
|
License-Expression: MIT
|
|
@@ -511,6 +511,11 @@ result = entries.create(attribute="Cores", entry={
|
|
|
511
511
|
# result -> [{"id": "<guid>", "code": "zb.b.xxx", "status": "success"}]
|
|
512
512
|
new_id = result[0]["id"]
|
|
513
513
|
|
|
514
|
+
# The code is generated by the server and read back with a second request.
|
|
515
|
+
# Skip that request when only the id is needed (imports, benchmarks):
|
|
516
|
+
result = entries.create(attribute="Cores", entry={...}, fetch_code=False)
|
|
517
|
+
# result -> [{"id": "<guid>", "status": "success"}]
|
|
518
|
+
|
|
514
519
|
# Bulk create
|
|
515
520
|
results = entries.create(attribute="Cores", entries=[
|
|
516
521
|
{"Alias": "bulk.001", "Event": "64PE428-02PC", "Number": 1},
|
|
@@ -529,6 +534,28 @@ entries.create(attribute="Cruise", entry={
|
|
|
529
534
|
})
|
|
530
535
|
```
|
|
531
536
|
|
|
537
|
+
#### `warm_select_cache` — pre-resolve select values before an import
|
|
538
|
+
|
|
539
|
+
Every select field value (`"Event": "64PE428-02PC"`, `"Device": "CTD"`) is
|
|
540
|
+
resolved with one search request the first time the manager sees it. An
|
|
541
|
+
import that references many different stations, devices or cruises pays one
|
|
542
|
+
request per distinct value. `warm_select_cache` loads the options of every
|
|
543
|
+
select field of an attribute up front and caches them by code, display name
|
|
544
|
+
and id, so the rows that follow resolve without a request:
|
|
545
|
+
|
|
546
|
+
```python
|
|
547
|
+
entries = EntryManager()
|
|
548
|
+
cached = entries.warm_select_cache("Event") # one request per select field (per 1000 options)
|
|
549
|
+
print(f"{cached} select options cached")
|
|
550
|
+
|
|
551
|
+
for row in rows:
|
|
552
|
+
entries.create(attribute="Event", entry=row, fetch_code=False) # one request per row
|
|
553
|
+
```
|
|
554
|
+
|
|
555
|
+
Values must match the server's spelling and case; anything else still falls
|
|
556
|
+
back to a search. Fields with more than `max_results` options (default 1000)
|
|
557
|
+
are warmed partially. The cache lives as long as the manager instance.
|
|
558
|
+
|
|
532
559
|
#### `update` — update one or many entries
|
|
533
560
|
|
|
534
561
|
```python
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|