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