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