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