das-cli 1.5.272__tar.gz → 1.6.5__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.5.272/das_cli.egg-info → das_cli-1.6.5}/PKG-INFO +41 -1
- {das_cli-1.5.272 → das_cli-1.6.5}/README.md +41 -1
- {das_cli-1.5.272 → das_cli-1.6.5}/das/authentication/auth.py +23 -5
- {das_cli-1.5.272 → das_cli-1.6.5}/das/cli.py +64 -5
- das_cli-1.6.5/das/common/api.py +192 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das/common/config.py +188 -2
- {das_cli-1.5.272 → das_cli-1.6.5}/das/common/enums.py +14 -0
- das_cli-1.6.5/das/common/errors.py +165 -0
- das_cli-1.6.5/das/common/exceptions.py +191 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das/managers/digital_objects_manager.py +81 -15
- {das_cli-1.5.272 → das_cli-1.6.5}/das/managers/entries_manager.py +78 -21
- {das_cli-1.5.272 → das_cli-1.6.5}/das/managers/search_manager.py +30 -6
- {das_cli-1.5.272 → das_cli-1.6.5}/das/services/attributes.py +4 -3
- {das_cli-1.5.272 → das_cli-1.6.5}/das/services/cache.py +4 -3
- {das_cli-1.5.272 → das_cli-1.6.5}/das/services/das_elastic_search.py +2 -5
- {das_cli-1.5.272 → das_cli-1.6.5}/das/services/digital_objects.py +111 -39
- {das_cli-1.5.272 → das_cli-1.6.5}/das/services/downloads.py +4 -6
- {das_cli-1.5.272 → das_cli-1.6.5}/das/services/entries.py +2 -9
- {das_cli-1.5.272 → das_cli-1.6.5}/das/services/entry_fields.py +2 -5
- {das_cli-1.5.272 → das_cli-1.6.5}/das/services/hangfire.py +2 -1
- {das_cli-1.5.272 → das_cli-1.6.5}/das/services/search.py +2 -4
- {das_cli-1.5.272 → das_cli-1.6.5}/das/services/users.py +2 -1
- {das_cli-1.5.272 → das_cli-1.6.5/das_cli.egg-info}/PKG-INFO +41 -1
- {das_cli-1.5.272 → das_cli-1.6.5}/das_cli.egg-info/SOURCES.txt +2 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/pyproject.toml +1 -1
- das_cli-1.5.272/das/common/api.py +0 -120
- {das_cli-1.5.272 → das_cli-1.6.5}/LICENSE +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/MANIFEST.in +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das/__init__.py +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das/ai/plugins/dasai.py +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das/ai/plugins/entries/entries_plugin.py +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das/app.py +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das/authentication/oauth.py +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das/authentication/secure_input.py +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das/common/entry_fields_constants.py +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das/common/file_utils.py +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das/managers/__init__.py +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das/managers/download_manager.py +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das/services/service_base.py +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das_cli.egg-info/dependency_links.txt +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das_cli.egg-info/entry_points.txt +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das_cli.egg-info/requires.txt +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/das_cli.egg-info/top_level.txt +0 -0
- {das_cli-1.5.272 → das_cli-1.6.5}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: das-cli
|
|
3
|
-
Version: 1.5
|
|
3
|
+
Version: 1.6.5
|
|
4
4
|
Summary: DAS api client.
|
|
5
5
|
Author: Royal Netherlands Institute for Sea Research
|
|
6
6
|
License-Expression: MIT
|
|
@@ -79,6 +79,7 @@ das entry get --code zb.b.1ub
|
|
|
79
79
|
- [Digital Objects](#digital-objects)
|
|
80
80
|
- [Downloads](#downloads)
|
|
81
81
|
- [Other CLI groups](#other-cli-groups)
|
|
82
|
+
- [Logging](#logging)
|
|
82
83
|
|
|
83
84
|
### Authentication
|
|
84
85
|
|
|
@@ -214,8 +215,37 @@ das config ssl-verify true
|
|
|
214
215
|
das config ssl-status
|
|
215
216
|
das config show
|
|
216
217
|
das config reset --force
|
|
218
|
+
|
|
219
|
+
# Logging
|
|
220
|
+
das config log-level DEBUG # TRACE, DEBUG, INFO, WARN (default), ERROR, FATAL
|
|
221
|
+
das config log-file C:\logs\das.log # also write logs to a file
|
|
222
|
+
das config log-file --clear # back to console only
|
|
217
223
|
```
|
|
218
224
|
|
|
225
|
+
#### Logging
|
|
226
|
+
|
|
227
|
+
The CLI logs diagnostics (HTTP requests and error details) through the `das`
|
|
228
|
+
logger. Control how much is shown and where it goes:
|
|
229
|
+
|
|
230
|
+
- **Level** — from most to least verbose: `TRACE`, `DEBUG`, `INFO`, `WARN`
|
|
231
|
+
(default), `ERROR`, `FATAL`. Set with `das config log-level <LEVEL>` or the
|
|
232
|
+
`DAS_LOG_LEVEL` environment variable.
|
|
233
|
+
- **Destination** — logs go to the console by default. Also write them to a file
|
|
234
|
+
with `das config log-file <path>` (parent folders are created automatically)
|
|
235
|
+
or the `DAS_LOG_FILE` environment variable; use `das config log-file --clear`
|
|
236
|
+
to go back to console-only. The file log includes timestamps and logger names
|
|
237
|
+
while the console stays terse.
|
|
238
|
+
|
|
239
|
+
```bash
|
|
240
|
+
# Verbose troubleshooting session written to a file
|
|
241
|
+
das config log-level DEBUG
|
|
242
|
+
das config log-file C:\logs\das.log
|
|
243
|
+
das search entries --attribute Cruise --query "cruisecode(*64PE*)"
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
> Tip: this is the diagnostic log for the CLI itself. For an entry's
|
|
247
|
+
> change/audit history, use [`das entry logs`](#logs-and-ownership) instead.
|
|
248
|
+
|
|
219
249
|
## Programmatic Usage (Python)
|
|
220
250
|
|
|
221
251
|
Two common patterns are supported.
|
|
@@ -774,6 +804,10 @@ DAS_API_URL=https://api.das-dev.nioz.nl
|
|
|
774
804
|
DAS_API_KEY=
|
|
775
805
|
VERIFY_SSL=True
|
|
776
806
|
|
|
807
|
+
# Logging
|
|
808
|
+
DAS_LOG_LEVEL=WARN
|
|
809
|
+
DAS_LOG_FILE=
|
|
810
|
+
|
|
777
811
|
# Test credentials (for integration tests)
|
|
778
812
|
API_URL=https://api.das-dev.nioz.nl
|
|
779
813
|
USER_NAME=
|
|
@@ -787,6 +821,8 @@ OPEN_AI_MODEL_ID=gpt-4o-mini
|
|
|
787
821
|
- `DAS_API_URL`: default API URL for app/managers when no explicit URL is provided.
|
|
788
822
|
- `DAS_API_KEY`: API key auth (takes precedence over stored token in auth layer).
|
|
789
823
|
- `VERIFY_SSL`: TLS verification (`True`/`False`).
|
|
824
|
+
- `DAS_LOG_LEVEL`: diagnostic log level (`TRACE`/`DEBUG`/`INFO`/`WARN`/`ERROR`/`FATAL`); overrides `das config log-level`.
|
|
825
|
+
- `DAS_LOG_FILE`: path to also write logs to a file; overrides `das config log-file`.
|
|
790
826
|
- `API_URL`, `USER_NAME`, `USER_PASSWORD`: used by integration tests.
|
|
791
827
|
|
|
792
828
|
## Unit Tests and Integration Tests
|
|
@@ -820,6 +856,10 @@ The tests are a good source of realistic payload examples, especially:
|
|
|
820
856
|
- prefer double quotes around query arguments containing `*`, `;`, and parentheses.
|
|
821
857
|
- No API URL configured:
|
|
822
858
|
- set `DAS_API_URL`, pass URL to `Das(...)`, or run `das login --api-url ...`.
|
|
859
|
+
- Need more detail on any error:
|
|
860
|
+
- raise verbosity with `das config log-level DEBUG` (optionally
|
|
861
|
+
`das config log-file <path>`) to see the full HTTP requests and error
|
|
862
|
+
details. See [Logging](#logging).
|
|
823
863
|
|
|
824
864
|
## Contributing
|
|
825
865
|
|
|
@@ -56,6 +56,7 @@ das entry get --code zb.b.1ub
|
|
|
56
56
|
- [Digital Objects](#digital-objects)
|
|
57
57
|
- [Downloads](#downloads)
|
|
58
58
|
- [Other CLI groups](#other-cli-groups)
|
|
59
|
+
- [Logging](#logging)
|
|
59
60
|
|
|
60
61
|
### Authentication
|
|
61
62
|
|
|
@@ -191,8 +192,37 @@ das config ssl-verify true
|
|
|
191
192
|
das config ssl-status
|
|
192
193
|
das config show
|
|
193
194
|
das config reset --force
|
|
195
|
+
|
|
196
|
+
# Logging
|
|
197
|
+
das config log-level DEBUG # TRACE, DEBUG, INFO, WARN (default), ERROR, FATAL
|
|
198
|
+
das config log-file C:\logs\das.log # also write logs to a file
|
|
199
|
+
das config log-file --clear # back to console only
|
|
194
200
|
```
|
|
195
201
|
|
|
202
|
+
#### Logging
|
|
203
|
+
|
|
204
|
+
The CLI logs diagnostics (HTTP requests and error details) through the `das`
|
|
205
|
+
logger. Control how much is shown and where it goes:
|
|
206
|
+
|
|
207
|
+
- **Level** — from most to least verbose: `TRACE`, `DEBUG`, `INFO`, `WARN`
|
|
208
|
+
(default), `ERROR`, `FATAL`. Set with `das config log-level <LEVEL>` or the
|
|
209
|
+
`DAS_LOG_LEVEL` environment variable.
|
|
210
|
+
- **Destination** — logs go to the console by default. Also write them to a file
|
|
211
|
+
with `das config log-file <path>` (parent folders are created automatically)
|
|
212
|
+
or the `DAS_LOG_FILE` environment variable; use `das config log-file --clear`
|
|
213
|
+
to go back to console-only. The file log includes timestamps and logger names
|
|
214
|
+
while the console stays terse.
|
|
215
|
+
|
|
216
|
+
```bash
|
|
217
|
+
# Verbose troubleshooting session written to a file
|
|
218
|
+
das config log-level DEBUG
|
|
219
|
+
das config log-file C:\logs\das.log
|
|
220
|
+
das search entries --attribute Cruise --query "cruisecode(*64PE*)"
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
> Tip: this is the diagnostic log for the CLI itself. For an entry's
|
|
224
|
+
> change/audit history, use [`das entry logs`](#logs-and-ownership) instead.
|
|
225
|
+
|
|
196
226
|
## Programmatic Usage (Python)
|
|
197
227
|
|
|
198
228
|
Two common patterns are supported.
|
|
@@ -751,6 +781,10 @@ DAS_API_URL=https://api.das-dev.nioz.nl
|
|
|
751
781
|
DAS_API_KEY=
|
|
752
782
|
VERIFY_SSL=True
|
|
753
783
|
|
|
784
|
+
# Logging
|
|
785
|
+
DAS_LOG_LEVEL=WARN
|
|
786
|
+
DAS_LOG_FILE=
|
|
787
|
+
|
|
754
788
|
# Test credentials (for integration tests)
|
|
755
789
|
API_URL=https://api.das-dev.nioz.nl
|
|
756
790
|
USER_NAME=
|
|
@@ -764,6 +798,8 @@ OPEN_AI_MODEL_ID=gpt-4o-mini
|
|
|
764
798
|
- `DAS_API_URL`: default API URL for app/managers when no explicit URL is provided.
|
|
765
799
|
- `DAS_API_KEY`: API key auth (takes precedence over stored token in auth layer).
|
|
766
800
|
- `VERIFY_SSL`: TLS verification (`True`/`False`).
|
|
801
|
+
- `DAS_LOG_LEVEL`: diagnostic log level (`TRACE`/`DEBUG`/`INFO`/`WARN`/`ERROR`/`FATAL`); overrides `das config log-level`.
|
|
802
|
+
- `DAS_LOG_FILE`: path to also write logs to a file; overrides `das config log-file`.
|
|
767
803
|
- `API_URL`, `USER_NAME`, `USER_PASSWORD`: used by integration tests.
|
|
768
804
|
|
|
769
805
|
## Unit Tests and Integration Tests
|
|
@@ -797,6 +833,10 @@ The tests are a good source of realistic payload examples, especially:
|
|
|
797
833
|
- prefer double quotes around query arguments containing `*`, `;`, and parentheses.
|
|
798
834
|
- No API URL configured:
|
|
799
835
|
- set `DAS_API_URL`, pass URL to `Das(...)`, or run `das login --api-url ...`.
|
|
836
|
+
- Need more detail on any error:
|
|
837
|
+
- raise verbosity with `das config log-level DEBUG` (optionally
|
|
838
|
+
`das config log-file <path>`) to see the full HTTP requests and error
|
|
839
|
+
details. See [Logging](#logging).
|
|
800
840
|
|
|
801
841
|
## Contributing
|
|
802
842
|
|
|
@@ -807,4 +847,4 @@ For bugs or feature requests, use the project issue tracker:
|
|
|
807
847
|
|
|
808
848
|
## License
|
|
809
849
|
|
|
810
|
-
MIT License
|
|
850
|
+
MIT License
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
from das.common.api import post_data
|
|
2
2
|
from das.common.config import save_token
|
|
3
|
+
from das.common.errors import extract_api_error
|
|
3
4
|
|
|
4
5
|
|
|
5
6
|
class Auth:
|
|
@@ -15,9 +16,18 @@ class Auth:
|
|
|
15
16
|
def authenticate(self, password):
|
|
16
17
|
"""
|
|
17
18
|
Authenticate the user and obtain an access token.
|
|
18
|
-
|
|
19
|
+
|
|
19
20
|
Args:
|
|
20
21
|
password (str): The password to authenticate with
|
|
22
|
+
|
|
23
|
+
Returns:
|
|
24
|
+
str: The access token on success.
|
|
25
|
+
|
|
26
|
+
Raises:
|
|
27
|
+
ValueError: With a descriptive message when authentication fails —
|
|
28
|
+
distinguishing bad credentials (the API's message) from
|
|
29
|
+
connection-level problems such as an untrusted TLS certificate
|
|
30
|
+
or an unreachable host.
|
|
21
31
|
"""
|
|
22
32
|
url = f"{self.base_url}/api/TokenAuth/Authenticate"
|
|
23
33
|
data = {
|
|
@@ -25,14 +35,22 @@ class Auth:
|
|
|
25
35
|
"password": password
|
|
26
36
|
}
|
|
27
37
|
response = post_data(url, data=data)
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
38
|
+
|
|
39
|
+
if not isinstance(response, dict):
|
|
40
|
+
raise ValueError("Unexpected response from the authentication endpoint.")
|
|
41
|
+
|
|
42
|
+
result = response.get("result") if response.get("success") is True else None
|
|
43
|
+
token = result.get("accessToken") if isinstance(result, dict) else None
|
|
44
|
+
|
|
45
|
+
if token:
|
|
46
|
+
self.token = token
|
|
32
47
|
save_token(self.token)
|
|
33
48
|
# Return silently, let the CLI handle success messages
|
|
34
49
|
return self.token
|
|
35
50
|
|
|
51
|
+
# Failure: surface the real reason (API message, SSL/cert or connection error).
|
|
52
|
+
raise ValueError(extract_api_error(response, "Authentication failed."))
|
|
53
|
+
|
|
36
54
|
if __name__ == "__main__":
|
|
37
55
|
# Example for testing authentication
|
|
38
56
|
import getpass
|
|
@@ -9,8 +9,10 @@ from das.common.config import (
|
|
|
9
9
|
load_openai_api_key, save_openai_api_key, clear_openai_api_key,
|
|
10
10
|
clear_token, _config_dir,
|
|
11
11
|
save_oauth_config, load_oauth_config, get_auth_type, set_auth_type,
|
|
12
|
-
save_token, save_token_expiry, save_refresh_token, clear_refresh_token
|
|
12
|
+
save_token, save_token_expiry, save_refresh_token, clear_refresh_token,
|
|
13
|
+
save_log_level, load_log_level, save_log_file, load_log_file, configure_logging,
|
|
13
14
|
)
|
|
15
|
+
from das.common.enums import LogLevel
|
|
14
16
|
|
|
15
17
|
from das.app import Das
|
|
16
18
|
from das.managers.download_manager import DownloadManager
|
|
@@ -166,8 +168,13 @@ def login(das_ctx, api_url, username, password, use_oauth, api_key, debug):
|
|
|
166
168
|
if not password:
|
|
167
169
|
password = click.prompt("Password", hide_input=True)
|
|
168
170
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
+
try:
|
|
172
|
+
client = das_ctx.get_client()
|
|
173
|
+
token = client.authenticate(username, password)
|
|
174
|
+
except Exception as e:
|
|
175
|
+
click.secho(f"❌ Authentication failed: {e}", fg="red")
|
|
176
|
+
return
|
|
177
|
+
|
|
171
178
|
if not token:
|
|
172
179
|
click.secho("❌ Authentication failed. Please check your credentials.", fg="red")
|
|
173
180
|
return
|
|
@@ -273,7 +280,8 @@ def search_help():
|
|
|
273
280
|
click.echo(" --max-results <n> Number of results per page (default: 10)")
|
|
274
281
|
|
|
275
282
|
click.secho("\nSorting:", fg="blue", bold=True)
|
|
276
|
-
click.echo(" --sort-by <field> Field to sort by (default:
|
|
283
|
+
click.echo(" --sort-by <field> Field to sort by (default: none — the server decides the order)")
|
|
284
|
+
click.echo(" Note: not every attribute has a 'Name' field (e.g. Cruise).")
|
|
277
285
|
click.echo(" --sort-order <order> Sort order: 'asc' or 'desc' (default: asc)")
|
|
278
286
|
click.echo("\n")
|
|
279
287
|
|
|
@@ -282,7 +290,7 @@ def search_help():
|
|
|
282
290
|
@click.option('--query', required=True, help='Search query string')
|
|
283
291
|
@click.option('--max-results', default=10, help='Maximum number of results to return')
|
|
284
292
|
@click.option('--page', default=1, help='Page number for paginated results')
|
|
285
|
-
@click.option('--sort-by', default='
|
|
293
|
+
@click.option('--sort-by', default='', help='Field to sort by (default: none — the server decides the order)')
|
|
286
294
|
@click.option('--sort-order', default='asc', type=click.Choice(['asc', 'desc']), help='Sort order (asc or desc)')
|
|
287
295
|
@click.option('--format', 'output_format', default='table', type=click.Choice(['table', 'json', 'compact']), help='Output format (table, json, or compact)')
|
|
288
296
|
@click.option('--raw', is_flag=True, help='Show raw response from API')
|
|
@@ -1141,6 +1149,48 @@ def get_ssl_status():
|
|
|
1141
1149
|
status = "enabled" if VERIFY_SSL else "disabled"
|
|
1142
1150
|
click.echo(f"SSL certificate verification is currently {status}")
|
|
1143
1151
|
|
|
1152
|
+
@config.command("log-level")
|
|
1153
|
+
@click.argument('level', type=click.Choice([l.name for l in LogLevel], case_sensitive=False), required=True)
|
|
1154
|
+
def set_log_level(level):
|
|
1155
|
+
"""Set the diagnostic log level.
|
|
1156
|
+
|
|
1157
|
+
Levels (most to least verbose): TRACE, DEBUG, INFO, WARN, ERROR, FATAL.
|
|
1158
|
+
|
|
1159
|
+
\b
|
|
1160
|
+
Example:
|
|
1161
|
+
das config log-level DEBUG
|
|
1162
|
+
"""
|
|
1163
|
+
save_log_level(level)
|
|
1164
|
+
configure_logging()
|
|
1165
|
+
click.secho(f"✓ Log level set to {level.upper()}", fg="green")
|
|
1166
|
+
|
|
1167
|
+
@config.command("log-file")
|
|
1168
|
+
@click.argument('path', required=False)
|
|
1169
|
+
@click.option('--clear', 'clear_path', is_flag=True, help='Stop writing logs to a file (console only)')
|
|
1170
|
+
def set_log_file(path, clear_path):
|
|
1171
|
+
"""Set (or clear) the file logs are written to.
|
|
1172
|
+
|
|
1173
|
+
\b
|
|
1174
|
+
Examples:
|
|
1175
|
+
# Write logs to a file
|
|
1176
|
+
das config log-file C:\\logs\\das.log
|
|
1177
|
+
|
|
1178
|
+
\b
|
|
1179
|
+
# Log to the console only
|
|
1180
|
+
das config log-file --clear
|
|
1181
|
+
"""
|
|
1182
|
+
if clear_path:
|
|
1183
|
+
save_log_file(None)
|
|
1184
|
+
configure_logging()
|
|
1185
|
+
click.secho("✓ File logging disabled (console only).", fg="green")
|
|
1186
|
+
return
|
|
1187
|
+
if not path:
|
|
1188
|
+
raise click.UsageError("Provide a file path, or use --clear to disable file logging.")
|
|
1189
|
+
save_log_file(path)
|
|
1190
|
+
configure_logging()
|
|
1191
|
+
resolved = load_log_file()
|
|
1192
|
+
click.secho(f"✓ Logs will be written to: {resolved}", fg="green")
|
|
1193
|
+
|
|
1144
1194
|
@config.command("show")
|
|
1145
1195
|
def config_show():
|
|
1146
1196
|
"""Show all current persistent settings"""
|
|
@@ -1168,10 +1218,19 @@ def config_show():
|
|
|
1168
1218
|
click.secho("Current settings", bold=True)
|
|
1169
1219
|
click.echo("─" * 40)
|
|
1170
1220
|
|
|
1221
|
+
# Logging
|
|
1222
|
+
log_level = load_log_level().name
|
|
1223
|
+
log_file = load_log_file() or "(console only)"
|
|
1224
|
+
|
|
1171
1225
|
click.secho(" Connection", fg="blue", bold=True)
|
|
1172
1226
|
click.echo(f" API URL : {api_url}")
|
|
1173
1227
|
click.echo(f" SSL verify : {'enabled' if ssl else 'disabled'}")
|
|
1174
1228
|
|
|
1229
|
+
click.echo("")
|
|
1230
|
+
click.secho(" Logging", fg="blue", bold=True)
|
|
1231
|
+
click.echo(f" Log level : {log_level}")
|
|
1232
|
+
click.echo(f" Log file : {log_file}")
|
|
1233
|
+
|
|
1175
1234
|
click.echo("")
|
|
1176
1235
|
click.secho(" Authentication", fg="blue", bold=True)
|
|
1177
1236
|
click.echo(f" Auth type : {auth_type}")
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import requests
|
|
4
|
+
from das.common.config import load_verify_ssl
|
|
5
|
+
from das.common.errors import describe_request_exception
|
|
6
|
+
|
|
7
|
+
logger = logging.getLogger("das")
|
|
8
|
+
|
|
9
|
+
# Default network timeout (connect, read) in seconds. Prevents the CLI from
|
|
10
|
+
# hanging indefinitely on an unreachable host.
|
|
11
|
+
DEFAULT_TIMEOUT = (10, 60)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _process_response(response, action: str):
|
|
15
|
+
"""Turn a ``requests.Response`` into a parsed dict or a structured error dict.
|
|
16
|
+
|
|
17
|
+
On a successful JSON parse the body is returned as-is (so ABP envelopes with
|
|
18
|
+
``success``/``error`` flow through to the services). When the HTTP status is
|
|
19
|
+
an error the status code is attached so callers can build a descriptive
|
|
20
|
+
message. A non-JSON body is reported with its status code and a snippet.
|
|
21
|
+
"""
|
|
22
|
+
# ``status_code`` is the authoritative error signal; ``response.ok`` is a
|
|
23
|
+
# derived convenience flag (``status_code < 400``). Prefer the former so the
|
|
24
|
+
# behaviour does not depend on ``.ok`` being populated.
|
|
25
|
+
is_http_error = response.status_code >= 400
|
|
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
|
+
|
|
31
|
+
try:
|
|
32
|
+
data = response.json()
|
|
33
|
+
except json.JSONDecodeError as json_err:
|
|
34
|
+
# Not JSON. If the status is an error, surface that clearly.
|
|
35
|
+
if is_http_error:
|
|
36
|
+
message = (
|
|
37
|
+
f"The server returned HTTP {response.status_code} "
|
|
38
|
+
f"({response.reason}) while trying to {action}."
|
|
39
|
+
)
|
|
40
|
+
logger.error(
|
|
41
|
+
"%s Response body: %s [correlationId: %s]",
|
|
42
|
+
message, response.text[:500], correlation_id,
|
|
43
|
+
)
|
|
44
|
+
return {
|
|
45
|
+
"error": message,
|
|
46
|
+
"status_code": response.status_code,
|
|
47
|
+
"correlation_id": correlation_id,
|
|
48
|
+
"raw_content": response.text[:500],
|
|
49
|
+
}
|
|
50
|
+
logger.error("Error decoding JSON response: %s", json_err)
|
|
51
|
+
return {
|
|
52
|
+
"error": f"Invalid JSON response: {json_err}",
|
|
53
|
+
"status_code": response.status_code,
|
|
54
|
+
"correlation_id": correlation_id,
|
|
55
|
+
"raw_content": response.text[:500],
|
|
56
|
+
}
|
|
57
|
+
|
|
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
|
+
)
|
|
71
|
+
return data
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def get_data(url, headers=None, params=None):
|
|
75
|
+
"""
|
|
76
|
+
Fetch data from a REST API endpoint.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
url (str): The API endpoint URL.
|
|
80
|
+
headers (dict, optional): Headers to include in the request.
|
|
81
|
+
params (dict, optional): Query parameters for the request.
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
dict: The JSON response from the API or an error message.
|
|
85
|
+
"""
|
|
86
|
+
logger.debug("GET %s", url)
|
|
87
|
+
try:
|
|
88
|
+
response = requests.get(
|
|
89
|
+
url, headers=headers, params=params,
|
|
90
|
+
verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
|
|
91
|
+
)
|
|
92
|
+
return _process_response(response, "fetch data")
|
|
93
|
+
except requests.RequestException as e:
|
|
94
|
+
message = describe_request_exception(e, url)
|
|
95
|
+
logger.error("Error fetching API data: %s", message)
|
|
96
|
+
return {"error": message}
|
|
97
|
+
|
|
98
|
+
def get_binary_response(url, headers=None, params=None, stream=True):
|
|
99
|
+
"""
|
|
100
|
+
Perform a GET request expected to return binary content.
|
|
101
|
+
|
|
102
|
+
Returns the raw requests.Response so callers can inspect headers
|
|
103
|
+
and stream content to disk.
|
|
104
|
+
"""
|
|
105
|
+
logger.debug("GET (binary) %s", url)
|
|
106
|
+
try:
|
|
107
|
+
response = requests.get(
|
|
108
|
+
url,
|
|
109
|
+
headers=headers,
|
|
110
|
+
params=params,
|
|
111
|
+
verify=load_verify_ssl(),
|
|
112
|
+
stream=stream,
|
|
113
|
+
timeout=DEFAULT_TIMEOUT,
|
|
114
|
+
)
|
|
115
|
+
response.raise_for_status()
|
|
116
|
+
return response
|
|
117
|
+
except requests.RequestException as e:
|
|
118
|
+
message = describe_request_exception(e, url)
|
|
119
|
+
logger.error("Error fetching binary API data: %s", message)
|
|
120
|
+
return {"error": message}
|
|
121
|
+
|
|
122
|
+
def post_data(url, headers=None, data=None):
|
|
123
|
+
"""
|
|
124
|
+
Send data to a REST API endpoint.
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
url (str): The API endpoint URL.
|
|
128
|
+
headers (dict, optional): Headers to include in the request.
|
|
129
|
+
data (dict, optional): The data to send in the request body.
|
|
130
|
+
|
|
131
|
+
Returns:
|
|
132
|
+
dict: The JSON response from the API or an error message.
|
|
133
|
+
"""
|
|
134
|
+
logger.debug("POST %s", url)
|
|
135
|
+
try:
|
|
136
|
+
response = requests.post(
|
|
137
|
+
url, headers=headers, json=data,
|
|
138
|
+
verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
|
|
139
|
+
)
|
|
140
|
+
return _process_response(response, "post data")
|
|
141
|
+
except requests.RequestException as e:
|
|
142
|
+
message = describe_request_exception(e, url)
|
|
143
|
+
logger.error("Error posting API data: %s", message)
|
|
144
|
+
return {"error": message}
|
|
145
|
+
|
|
146
|
+
def put_data(url, headers=None, data=None):
|
|
147
|
+
"""
|
|
148
|
+
Update data at a REST API endpoint.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
url (str): The API endpoint URL.
|
|
152
|
+
headers (dict, optional): Headers to include in the request.
|
|
153
|
+
data (dict, optional): The data to send in the request body.
|
|
154
|
+
|
|
155
|
+
Returns:
|
|
156
|
+
dict: The JSON response from the API or an error message.
|
|
157
|
+
"""
|
|
158
|
+
logger.debug("PUT %s", url)
|
|
159
|
+
try:
|
|
160
|
+
response = requests.put(
|
|
161
|
+
url, headers=headers, json=data,
|
|
162
|
+
verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
|
|
163
|
+
)
|
|
164
|
+
return _process_response(response, "update data")
|
|
165
|
+
except requests.RequestException as e:
|
|
166
|
+
message = describe_request_exception(e, url)
|
|
167
|
+
logger.error("Error updating API data: %s", message)
|
|
168
|
+
return {"error": message}
|
|
169
|
+
|
|
170
|
+
def delete_data(url, headers=None, data=None):
|
|
171
|
+
"""
|
|
172
|
+
Delete data from a REST API endpoint.
|
|
173
|
+
|
|
174
|
+
Args:
|
|
175
|
+
url (str): The API endpoint URL.
|
|
176
|
+
headers (dict, optional): Headers to include in the request.
|
|
177
|
+
data (dict, optional): The data to send in the request body.
|
|
178
|
+
|
|
179
|
+
Returns:
|
|
180
|
+
dict: The JSON response from the API or an error message.
|
|
181
|
+
"""
|
|
182
|
+
logger.debug("DELETE %s", url)
|
|
183
|
+
try:
|
|
184
|
+
response = requests.delete(
|
|
185
|
+
url, headers=headers, json=data,
|
|
186
|
+
verify=load_verify_ssl(), timeout=DEFAULT_TIMEOUT,
|
|
187
|
+
)
|
|
188
|
+
return _process_response(response, "delete data")
|
|
189
|
+
except requests.RequestException as e:
|
|
190
|
+
message = describe_request_exception(e, url)
|
|
191
|
+
logger.error("Error deleting API data: %s", message)
|
|
192
|
+
return {"error": message}
|