aind-metadata-service-client 2.6.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ """API response object."""
2
+
3
+ from __future__ import annotations
4
+ from typing import Optional, Generic, Mapping, TypeVar
5
+ from pydantic import Field, StrictInt, StrictBytes, BaseModel
6
+
7
+ T = TypeVar("T")
8
+
9
+ class ApiResponse(BaseModel, Generic[T]):
10
+ """
11
+ API response object
12
+ """
13
+
14
+ status_code: StrictInt = Field(description="HTTP status code")
15
+ headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers")
16
+ data: T = Field(description="Deserialized data given the data type")
17
+ raw_data: StrictBytes = Field(description="Raw data (HTTP response body)")
18
+
19
+ model_config = {
20
+ "arbitrary_types_allowed": True
21
+ }
@@ -0,0 +1,572 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ aind-metadata-service
5
+
6
+ ## aind-metadata-service Service to pull data from example backend.
7
+
8
+ The version of the OpenAPI document: 2.6.0
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
13
+
14
+
15
+ import copy
16
+ import http.client as httplib
17
+ import logging
18
+ from logging import FileHandler
19
+ import multiprocessing
20
+ import sys
21
+ from typing import Any, ClassVar, Dict, List, Literal, Optional, TypedDict, Union
22
+ from typing_extensions import NotRequired, Self
23
+
24
+ import urllib3
25
+
26
+
27
+ JSON_SCHEMA_VALIDATION_KEYWORDS = {
28
+ 'multipleOf', 'maximum', 'exclusiveMaximum',
29
+ 'minimum', 'exclusiveMinimum', 'maxLength',
30
+ 'minLength', 'pattern', 'maxItems', 'minItems'
31
+ }
32
+
33
+ ServerVariablesT = Dict[str, str]
34
+
35
+ GenericAuthSetting = TypedDict(
36
+ "GenericAuthSetting",
37
+ {
38
+ "type": str,
39
+ "in": str,
40
+ "key": str,
41
+ "value": str,
42
+ },
43
+ )
44
+
45
+
46
+ OAuth2AuthSetting = TypedDict(
47
+ "OAuth2AuthSetting",
48
+ {
49
+ "type": Literal["oauth2"],
50
+ "in": Literal["header"],
51
+ "key": Literal["Authorization"],
52
+ "value": str,
53
+ },
54
+ )
55
+
56
+
57
+ APIKeyAuthSetting = TypedDict(
58
+ "APIKeyAuthSetting",
59
+ {
60
+ "type": Literal["api_key"],
61
+ "in": str,
62
+ "key": str,
63
+ "value": Optional[str],
64
+ },
65
+ )
66
+
67
+
68
+ BasicAuthSetting = TypedDict(
69
+ "BasicAuthSetting",
70
+ {
71
+ "type": Literal["basic"],
72
+ "in": Literal["header"],
73
+ "key": Literal["Authorization"],
74
+ "value": Optional[str],
75
+ },
76
+ )
77
+
78
+
79
+ BearerFormatAuthSetting = TypedDict(
80
+ "BearerFormatAuthSetting",
81
+ {
82
+ "type": Literal["bearer"],
83
+ "in": Literal["header"],
84
+ "format": Literal["JWT"],
85
+ "key": Literal["Authorization"],
86
+ "value": str,
87
+ },
88
+ )
89
+
90
+
91
+ BearerAuthSetting = TypedDict(
92
+ "BearerAuthSetting",
93
+ {
94
+ "type": Literal["bearer"],
95
+ "in": Literal["header"],
96
+ "key": Literal["Authorization"],
97
+ "value": str,
98
+ },
99
+ )
100
+
101
+
102
+ HTTPSignatureAuthSetting = TypedDict(
103
+ "HTTPSignatureAuthSetting",
104
+ {
105
+ "type": Literal["http-signature"],
106
+ "in": Literal["header"],
107
+ "key": Literal["Authorization"],
108
+ "value": None,
109
+ },
110
+ )
111
+
112
+
113
+ AuthSettings = TypedDict(
114
+ "AuthSettings",
115
+ {
116
+ },
117
+ total=False,
118
+ )
119
+
120
+
121
+ class HostSettingVariable(TypedDict):
122
+ description: str
123
+ default_value: str
124
+ enum_values: List[str]
125
+
126
+
127
+ class HostSetting(TypedDict):
128
+ url: str
129
+ description: str
130
+ variables: NotRequired[Dict[str, HostSettingVariable]]
131
+
132
+
133
+ class Configuration:
134
+ """This class contains various settings of the API client.
135
+
136
+ :param host: Base url.
137
+ :param ignore_operation_servers
138
+ Boolean to ignore operation servers for the API client.
139
+ Config will use `host` as the base url regardless of the operation servers.
140
+ :param api_key: Dict to store API key(s).
141
+ Each entry in the dict specifies an API key.
142
+ The dict key is the name of the security scheme in the OAS specification.
143
+ The dict value is the API key secret.
144
+ :param api_key_prefix: Dict to store API prefix (e.g. Bearer).
145
+ The dict key is the name of the security scheme in the OAS specification.
146
+ The dict value is an API key prefix when generating the auth data.
147
+ :param username: Username for HTTP basic authentication.
148
+ :param password: Password for HTTP basic authentication.
149
+ :param access_token: Access token.
150
+ :param server_index: Index to servers configuration.
151
+ :param server_variables: Mapping with string values to replace variables in
152
+ templated server configuration. The validation of enums is performed for
153
+ variables with defined enum values before.
154
+ :param server_operation_index: Mapping from operation ID to an index to server
155
+ configuration.
156
+ :param server_operation_variables: Mapping from operation ID to a mapping with
157
+ string values to replace variables in templated server configuration.
158
+ The validation of enums is performed for variables with defined enum
159
+ values before.
160
+ :param ssl_ca_cert: str - the path to a file of concatenated CA certificates
161
+ in PEM format.
162
+ :param retries: Number of retries for API requests.
163
+ :param ca_cert_data: verify the peer using concatenated CA certificate data
164
+ in PEM (str) or DER (bytes) format.
165
+
166
+ """
167
+
168
+ _default: ClassVar[Optional[Self]] = None
169
+
170
+ def __init__(
171
+ self,
172
+ host: Optional[str]=None,
173
+ api_key: Optional[Dict[str, str]]=None,
174
+ api_key_prefix: Optional[Dict[str, str]]=None,
175
+ username: Optional[str]=None,
176
+ password: Optional[str]=None,
177
+ access_token: Optional[str]=None,
178
+ server_index: Optional[int]=None,
179
+ server_variables: Optional[ServerVariablesT]=None,
180
+ server_operation_index: Optional[Dict[int, int]]=None,
181
+ server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None,
182
+ ignore_operation_servers: bool=False,
183
+ ssl_ca_cert: Optional[str]=None,
184
+ retries: Optional[int] = None,
185
+ ca_cert_data: Optional[Union[str, bytes]] = None,
186
+ *,
187
+ debug: Optional[bool] = None,
188
+ ) -> None:
189
+ """Constructor
190
+ """
191
+ self._base_path = "http://localhost" if host is None else host
192
+ """Default Base url
193
+ """
194
+ self.server_index = 0 if server_index is None and host is None else server_index
195
+ self.server_operation_index = server_operation_index or {}
196
+ """Default server index
197
+ """
198
+ self.server_variables = server_variables or {}
199
+ self.server_operation_variables = server_operation_variables or {}
200
+ """Default server variables
201
+ """
202
+ self.ignore_operation_servers = ignore_operation_servers
203
+ """Ignore operation servers
204
+ """
205
+ self.temp_folder_path = None
206
+ """Temp file folder for downloading files
207
+ """
208
+ # Authentication Settings
209
+ self.api_key = {}
210
+ if api_key:
211
+ self.api_key = api_key
212
+ """dict to store API key(s)
213
+ """
214
+ self.api_key_prefix = {}
215
+ if api_key_prefix:
216
+ self.api_key_prefix = api_key_prefix
217
+ """dict to store API prefix (e.g. Bearer)
218
+ """
219
+ self.refresh_api_key_hook = None
220
+ """function hook to refresh API key if expired
221
+ """
222
+ self.username = username
223
+ """Username for HTTP basic authentication
224
+ """
225
+ self.password = password
226
+ """Password for HTTP basic authentication
227
+ """
228
+ self.access_token = access_token
229
+ """Access token
230
+ """
231
+ self.logger = {}
232
+ """Logging Settings
233
+ """
234
+ self.logger["package_logger"] = logging.getLogger("aind_metadata_service_client")
235
+ self.logger["urllib3_logger"] = logging.getLogger("urllib3")
236
+ self.logger_format = '%(asctime)s %(levelname)s %(message)s'
237
+ """Log format
238
+ """
239
+ self.logger_stream_handler = None
240
+ """Log stream handler
241
+ """
242
+ self.logger_file_handler: Optional[FileHandler] = None
243
+ """Log file handler
244
+ """
245
+ self.logger_file = None
246
+ """Debug file location
247
+ """
248
+ if debug is not None:
249
+ self.debug = debug
250
+ else:
251
+ self.__debug = False
252
+ """Debug switch
253
+ """
254
+
255
+ self.verify_ssl = True
256
+ """SSL/TLS verification
257
+ Set this to false to skip verifying SSL certificate when calling API
258
+ from https server.
259
+ """
260
+ self.ssl_ca_cert = ssl_ca_cert
261
+ """Set this to customize the certificate file to verify the peer.
262
+ """
263
+ self.ca_cert_data = ca_cert_data
264
+ """Set this to verify the peer using PEM (str) or DER (bytes)
265
+ certificate data.
266
+ """
267
+ self.cert_file = None
268
+ """client certificate file
269
+ """
270
+ self.key_file = None
271
+ """client key file
272
+ """
273
+ self.assert_hostname = None
274
+ """Set this to True/False to enable/disable SSL hostname verification.
275
+ """
276
+ self.tls_server_name = None
277
+ """SSL/TLS Server Name Indication (SNI)
278
+ Set this to the SNI value expected by the server.
279
+ """
280
+
281
+ self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
282
+ """urllib3 connection pool's maximum number of connections saved
283
+ per pool. urllib3 uses 1 connection as default value, but this is
284
+ not the best value when you are making a lot of possibly parallel
285
+ requests to the same host, which is often the case here.
286
+ cpu_count * 5 is used as default value to increase performance.
287
+ """
288
+
289
+ self.proxy: Optional[str] = None
290
+ """Proxy URL
291
+ """
292
+ self.proxy_headers = None
293
+ """Proxy headers
294
+ """
295
+ self.safe_chars_for_path_param = ''
296
+ """Safe chars for path_param
297
+ """
298
+ self.retries = retries
299
+ """Adding retries to override urllib3 default value 3
300
+ """
301
+ # Enable client side validation
302
+ self.client_side_validation = True
303
+
304
+ self.socket_options = None
305
+ """Options to pass down to the underlying urllib3 socket
306
+ """
307
+
308
+ self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z"
309
+ """datetime format
310
+ """
311
+
312
+ self.date_format = "%Y-%m-%d"
313
+ """date format
314
+ """
315
+
316
+ def __deepcopy__(self, memo: Dict[int, Any]) -> Self:
317
+ cls = self.__class__
318
+ result = cls.__new__(cls)
319
+ memo[id(self)] = result
320
+ for k, v in self.__dict__.items():
321
+ if k not in ('logger', 'logger_file_handler'):
322
+ setattr(result, k, copy.deepcopy(v, memo))
323
+ # shallow copy of loggers
324
+ result.logger = copy.copy(self.logger)
325
+ # use setters to configure loggers
326
+ result.logger_file = self.logger_file
327
+ result.debug = self.debug
328
+ return result
329
+
330
+ def __setattr__(self, name: str, value: Any) -> None:
331
+ object.__setattr__(self, name, value)
332
+
333
+ @classmethod
334
+ def set_default(cls, default: Optional[Self]) -> None:
335
+ """Set default instance of configuration.
336
+
337
+ It stores default configuration, which can be
338
+ returned by get_default_copy method.
339
+
340
+ :param default: object of Configuration
341
+ """
342
+ cls._default = default
343
+
344
+ @classmethod
345
+ def get_default_copy(cls) -> Self:
346
+ """Deprecated. Please use `get_default` instead.
347
+
348
+ Deprecated. Please use `get_default` instead.
349
+
350
+ :return: The configuration object.
351
+ """
352
+ return cls.get_default()
353
+
354
+ @classmethod
355
+ def get_default(cls) -> Self:
356
+ """Return the default configuration.
357
+
358
+ This method returns newly created, based on default constructor,
359
+ object of Configuration class or returns a copy of default
360
+ configuration.
361
+
362
+ :return: The configuration object.
363
+ """
364
+ if cls._default is None:
365
+ cls._default = cls()
366
+ return cls._default
367
+
368
+ @property
369
+ def logger_file(self) -> Optional[str]:
370
+ """The logger file.
371
+
372
+ If the logger_file is None, then add stream handler and remove file
373
+ handler. Otherwise, add file handler and remove stream handler.
374
+
375
+ :param value: The logger_file path.
376
+ :type: str
377
+ """
378
+ return self.__logger_file
379
+
380
+ @logger_file.setter
381
+ def logger_file(self, value: Optional[str]) -> None:
382
+ """The logger file.
383
+
384
+ If the logger_file is None, then add stream handler and remove file
385
+ handler. Otherwise, add file handler and remove stream handler.
386
+
387
+ :param value: The logger_file path.
388
+ :type: str
389
+ """
390
+ self.__logger_file = value
391
+ if self.__logger_file:
392
+ # If set logging file,
393
+ # then add file handler and remove stream handler.
394
+ self.logger_file_handler = logging.FileHandler(self.__logger_file)
395
+ self.logger_file_handler.setFormatter(self.logger_formatter)
396
+ for _, logger in self.logger.items():
397
+ logger.addHandler(self.logger_file_handler)
398
+
399
+ @property
400
+ def debug(self) -> bool:
401
+ """Debug status
402
+
403
+ :param value: The debug status, True or False.
404
+ :type: bool
405
+ """
406
+ return self.__debug
407
+
408
+ @debug.setter
409
+ def debug(self, value: bool) -> None:
410
+ """Debug status
411
+
412
+ :param value: The debug status, True or False.
413
+ :type: bool
414
+ """
415
+ self.__debug = value
416
+ if self.__debug:
417
+ # if debug status is True, turn on debug logging
418
+ for _, logger in self.logger.items():
419
+ logger.setLevel(logging.DEBUG)
420
+ # turn on httplib debug
421
+ httplib.HTTPConnection.debuglevel = 1
422
+ else:
423
+ # if debug status is False, turn off debug logging,
424
+ # setting log level to default `logging.WARNING`
425
+ for _, logger in self.logger.items():
426
+ logger.setLevel(logging.WARNING)
427
+ # turn off httplib debug
428
+ httplib.HTTPConnection.debuglevel = 0
429
+
430
+ @property
431
+ def logger_format(self) -> str:
432
+ """The logger format.
433
+
434
+ The logger_formatter will be updated when sets logger_format.
435
+
436
+ :param value: The format string.
437
+ :type: str
438
+ """
439
+ return self.__logger_format
440
+
441
+ @logger_format.setter
442
+ def logger_format(self, value: str) -> None:
443
+ """The logger format.
444
+
445
+ The logger_formatter will be updated when sets logger_format.
446
+
447
+ :param value: The format string.
448
+ :type: str
449
+ """
450
+ self.__logger_format = value
451
+ self.logger_formatter = logging.Formatter(self.__logger_format)
452
+
453
+ def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]:
454
+ """Gets API key (with prefix if set).
455
+
456
+ :param identifier: The identifier of apiKey.
457
+ :param alias: The alternative identifier of apiKey.
458
+ :return: The token for api key authentication.
459
+ """
460
+ if self.refresh_api_key_hook is not None:
461
+ self.refresh_api_key_hook(self)
462
+ key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None)
463
+ if key:
464
+ prefix = self.api_key_prefix.get(identifier)
465
+ if prefix:
466
+ return "%s %s" % (prefix, key)
467
+ else:
468
+ return key
469
+
470
+ return None
471
+
472
+ def get_basic_auth_token(self) -> Optional[str]:
473
+ """Gets HTTP basic authentication header (string).
474
+
475
+ :return: The token for basic HTTP authentication.
476
+ """
477
+ username = ""
478
+ if self.username is not None:
479
+ username = self.username
480
+ password = ""
481
+ if self.password is not None:
482
+ password = self.password
483
+ return urllib3.util.make_headers(
484
+ basic_auth=username + ':' + password
485
+ ).get('authorization')
486
+
487
+ def auth_settings(self)-> AuthSettings:
488
+ """Gets Auth Settings dict for api client.
489
+
490
+ :return: The Auth Settings information dict.
491
+ """
492
+ auth: AuthSettings = {}
493
+ return auth
494
+
495
+ def to_debug_report(self) -> str:
496
+ """Gets the essential information for debugging.
497
+
498
+ :return: The report for debugging.
499
+ """
500
+ return "Python SDK Debug Report:\n"\
501
+ "OS: {env}\n"\
502
+ "Python Version: {pyversion}\n"\
503
+ "Version of the API: 2.6.0\n"\
504
+ "SDK Package Version: 2.6.0".\
505
+ format(env=sys.platform, pyversion=sys.version)
506
+
507
+ def get_host_settings(self) -> List[HostSetting]:
508
+ """Gets an array of host settings
509
+
510
+ :return: An array of host settings
511
+ """
512
+ return [
513
+ {
514
+ 'url': "",
515
+ 'description': "No description provided",
516
+ }
517
+ ]
518
+
519
+ def get_host_from_settings(
520
+ self,
521
+ index: Optional[int],
522
+ variables: Optional[ServerVariablesT]=None,
523
+ servers: Optional[List[HostSetting]]=None,
524
+ ) -> str:
525
+ """Gets host URL based on the index and variables
526
+ :param index: array index of the host settings
527
+ :param variables: hash of variable and the corresponding value
528
+ :param servers: an array of host settings or None
529
+ :return: URL based on host settings
530
+ """
531
+ if index is None:
532
+ return self._base_path
533
+
534
+ variables = {} if variables is None else variables
535
+ servers = self.get_host_settings() if servers is None else servers
536
+
537
+ try:
538
+ server = servers[index]
539
+ except IndexError:
540
+ raise ValueError(
541
+ "Invalid index {0} when selecting the host settings. "
542
+ "Must be less than {1}".format(index, len(servers)))
543
+
544
+ url = server['url']
545
+
546
+ # go through variables and replace placeholders
547
+ for variable_name, variable in server.get('variables', {}).items():
548
+ used_value = variables.get(
549
+ variable_name, variable['default_value'])
550
+
551
+ if 'enum_values' in variable \
552
+ and used_value not in variable['enum_values']:
553
+ raise ValueError(
554
+ "The variable `{0}` in the host URL has invalid value "
555
+ "{1}. Must be {2}.".format(
556
+ variable_name, variables[variable_name],
557
+ variable['enum_values']))
558
+
559
+ url = url.replace("{" + variable_name + "}", used_value)
560
+
561
+ return url
562
+
563
+ @property
564
+ def host(self) -> str:
565
+ """Return generated host."""
566
+ return self.get_host_from_settings(self.server_index, variables=self.server_variables)
567
+
568
+ @host.setter
569
+ def host(self, value: str) -> None:
570
+ """Fix base path."""
571
+ self._base_path = value
572
+ self.server_index = None