stract-api 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.
Files changed (61) hide show
  1. stract_api/__init__.py +141 -0
  2. stract_api/api/__init__.py +16 -0
  3. stract_api/api/account_api.py +1098 -0
  4. stract_api/api/account_credit_ledger_api.py +286 -0
  5. stract_api/api/api_key_api.py +286 -0
  6. stract_api/api/catalog_api.py +837 -0
  7. stract_api/api/credits_api.py +534 -0
  8. stract_api/api/document_api.py +2799 -0
  9. stract_api/api/field_api.py +1168 -0
  10. stract_api/api/job_api.py +2857 -0
  11. stract_api/api/job_document_api.py +575 -0
  12. stract_api/api/llm_model_api.py +286 -0
  13. stract_api/api/struct_api.py +837 -0
  14. stract_api/api/user_api.py +572 -0
  15. stract_api/api_client.py +866 -0
  16. stract_api/api_response.py +21 -0
  17. stract_api/configuration.py +655 -0
  18. stract_api/exceptions.py +219 -0
  19. stract_api/models/__init__.py +52 -0
  20. stract_api/models/account.py +130 -0
  21. stract_api/models/account_credit_cache.py +112 -0
  22. stract_api/models/account_credit_ledger.py +125 -0
  23. stract_api/models/account_user.py +104 -0
  24. stract_api/models/account_user_role.py +38 -0
  25. stract_api/models/api_key.py +102 -0
  26. stract_api/models/catalog.py +100 -0
  27. stract_api/models/create_account_user_request.py +97 -0
  28. stract_api/models/create_catalog_request.py +90 -0
  29. stract_api/models/create_field_request.py +102 -0
  30. stract_api/models/create_job_request.py +109 -0
  31. stract_api/models/create_struct_request.py +90 -0
  32. stract_api/models/deleted_document.py +91 -0
  33. stract_api/models/deleted_field.py +91 -0
  34. stract_api/models/document.py +107 -0
  35. stract_api/models/document_link.py +90 -0
  36. stract_api/models/document_processing_status.py +39 -0
  37. stract_api/models/document_text.py +95 -0
  38. stract_api/models/edit_account_request.py +90 -0
  39. stract_api/models/edit_field_request.py +102 -0
  40. stract_api/models/edit_my_user_request.py +92 -0
  41. stract_api/models/field_type.py +42 -0
  42. stract_api/models/job.py +129 -0
  43. stract_api/models/job_document.py +123 -0
  44. stract_api/models/job_output.py +98 -0
  45. stract_api/models/job_output_record.py +103 -0
  46. stract_api/models/job_status.py +41 -0
  47. stract_api/models/llm_model.py +126 -0
  48. stract_api/models/login_request.py +92 -0
  49. stract_api/models/login_response.py +90 -0
  50. stract_api/models/model_field.py +110 -0
  51. stract_api/models/struct.py +100 -0
  52. stract_api/models/sync_text_job_request.py +118 -0
  53. stract_api/models/upload_text_document_request.py +93 -0
  54. stract_api/models/user.py +102 -0
  55. stract_api/py.typed +0 -0
  56. stract_api/rest.py +335 -0
  57. stract_api-0.1.0.dist-info/METADATA +266 -0
  58. stract_api-0.1.0.dist-info/RECORD +61 -0
  59. stract_api-0.1.0.dist-info/WHEEL +5 -0
  60. stract_api-0.1.0.dist-info/licenses/LICENSE +21 -0
  61. stract_api-0.1.0.dist-info/top_level.txt +1 -0
@@ -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,655 @@
1
+ """
2
+ Stract API
3
+
4
+ Get structured output from unstructured inputs ## Machine authentication Programmatic access to the API is authenticated with an API key. Include the API key in every request as a bearer token in the `authorization` header: ``` authorization: bearer [apiKey] ``` ## SDKs Official SDKs are available for the following languages: - **Node (JavaScript / TypeScript)**: [`stract-api` on npm](https://www.npmjs.com/package/stract-api) - **Java (17+)**: [`com.stract-api:stract-api` on Maven Central](https://central.sonatype.com/artifact/com.stract-api/stract-api)
5
+
6
+ The version of the OpenAPI document: 0.9.4
7
+ Contact: matt@stract-api.com
8
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
9
+
10
+ Do not edit the class manually.
11
+ """ # noqa: E501
12
+
13
+
14
+ import copy
15
+ import http.client as httplib
16
+ import logging
17
+ from logging import FileHandler
18
+ import multiprocessing
19
+ import ssl
20
+ import sys
21
+ from typing import Any, ClassVar, Dict, List, Literal, Optional, TypedDict, Union
22
+ from urllib.parse import urlparse
23
+ from urllib.request import getproxies
24
+ from typing_extensions import NotRequired, Self
25
+
26
+ import urllib3
27
+
28
+
29
+ JSON_SCHEMA_VALIDATION_KEYWORDS = {
30
+ 'multipleOf', 'maximum', 'exclusiveMaximum',
31
+ 'minimum', 'exclusiveMinimum', 'maxLength',
32
+ 'minLength', 'pattern', 'maxItems', 'minItems'
33
+ }
34
+
35
+ ServerVariablesT = Dict[str, str]
36
+
37
+ GenericAuthSetting = TypedDict(
38
+ "GenericAuthSetting",
39
+ {
40
+ "type": str,
41
+ "in": str,
42
+ "key": str,
43
+ "value": str,
44
+ },
45
+ )
46
+
47
+
48
+ OAuth2AuthSetting = TypedDict(
49
+ "OAuth2AuthSetting",
50
+ {
51
+ "type": Literal["oauth2"],
52
+ "in": Literal["header"],
53
+ "key": Literal["Authorization"],
54
+ "value": str,
55
+ },
56
+ )
57
+
58
+
59
+ APIKeyAuthSetting = TypedDict(
60
+ "APIKeyAuthSetting",
61
+ {
62
+ "type": Literal["api_key"],
63
+ "in": str,
64
+ "key": str,
65
+ "value": Optional[str],
66
+ },
67
+ )
68
+
69
+
70
+ BasicAuthSetting = TypedDict(
71
+ "BasicAuthSetting",
72
+ {
73
+ "type": Literal["basic"],
74
+ "in": Literal["header"],
75
+ "key": Literal["Authorization"],
76
+ "value": Optional[str],
77
+ },
78
+ )
79
+
80
+
81
+ BearerFormatAuthSetting = TypedDict(
82
+ "BearerFormatAuthSetting",
83
+ {
84
+ "type": Literal["bearer"],
85
+ "in": Literal["header"],
86
+ "format": Literal["JWT"],
87
+ "key": Literal["Authorization"],
88
+ "value": str,
89
+ },
90
+ )
91
+
92
+
93
+ BearerAuthSetting = TypedDict(
94
+ "BearerAuthSetting",
95
+ {
96
+ "type": Literal["bearer"],
97
+ "in": Literal["header"],
98
+ "key": Literal["Authorization"],
99
+ "value": str,
100
+ },
101
+ )
102
+
103
+
104
+ HTTPSignatureAuthSetting = TypedDict(
105
+ "HTTPSignatureAuthSetting",
106
+ {
107
+ "type": Literal["http-signature"],
108
+ "in": Literal["header"],
109
+ "key": Literal["Authorization"],
110
+ "value": None,
111
+ },
112
+ )
113
+
114
+
115
+ AuthSettings = TypedDict(
116
+ "AuthSettings",
117
+ {
118
+ "bearerAuth": BearerAuthSetting,
119
+ },
120
+ total=False,
121
+ )
122
+
123
+
124
+ class HostSettingVariable(TypedDict):
125
+ description: str
126
+ default_value: str
127
+ enum_values: List[str]
128
+
129
+
130
+ class HostSetting(TypedDict):
131
+ url: str
132
+ description: str
133
+ variables: NotRequired[Dict[str, HostSettingVariable]]
134
+
135
+
136
+ class Configuration:
137
+ """This class contains various settings of the API client.
138
+
139
+ :param host: Base url.
140
+ :param ignore_operation_servers
141
+ Boolean to ignore operation servers for the API client.
142
+ Config will use `host` as the base url regardless of the operation servers.
143
+ :param api_key: Dict to store API key(s).
144
+ Each entry in the dict specifies an API key.
145
+ The dict key is the name of the security scheme in the OAS specification.
146
+ The dict value is the API key secret.
147
+ :param api_key_prefix: Dict to store API prefix (e.g. Bearer).
148
+ The dict key is the name of the security scheme in the OAS specification.
149
+ The dict value is an API key prefix when generating the auth data.
150
+ :param username: Username for HTTP basic authentication.
151
+ :param password: Password for HTTP basic authentication.
152
+ :param access_token: Access token.
153
+ :param server_index: Index to servers configuration.
154
+ :param server_variables: Mapping with string values to replace variables in
155
+ templated server configuration. The validation of enums is performed for
156
+ variables with defined enum values before.
157
+ :param server_operation_index: Mapping from operation ID to an index to server
158
+ configuration.
159
+ :param server_operation_variables: Mapping from operation ID to a mapping with
160
+ string values to replace variables in templated server configuration.
161
+ The validation of enums is performed for variables with defined enum
162
+ values before.
163
+ :param verify_ssl: bool - Set this to false to skip verifying SSL certificate
164
+ when calling API from https server.
165
+ :param ssl_ca_cert: str - the path to a file of concatenated CA certificates
166
+ in PEM format.
167
+ :param retries: int | urllib3.util.retry.Retry - Retry configuration.
168
+ :param ca_cert_data: verify the peer using concatenated CA certificate data
169
+ in PEM (str) or DER (bytes) format.
170
+ :param cert_file: the path to a client certificate file, for mTLS.
171
+ :param key_file: the path to a client key file, for mTLS.
172
+ :param assert_hostname: Set this to True/False to enable/disable SSL hostname verification.
173
+ :param tls_server_name: SSL/TLS Server Name Indication (SNI). Set this to the SNI value expected by the server.
174
+ :param connection_pool_maxsize: Connection pool max size. None in the constructor is coerced to 100 for async and cpu_count * 5 for sync.
175
+ :param proxy: Proxy URL.
176
+ :param no_proxy: Comma-separated hosts that bypass the proxy.
177
+ :param proxy_headers: Proxy headers.
178
+ :param proxy_ssl_context: SSL context used only for the TLS handshake with the proxy itself, independent of the destination TLS settings.
179
+ :param safe_chars_for_path_param: Safe characters for path parameter encoding.
180
+ :param client_side_validation: Enable client-side validation. Default True.
181
+ :param socket_options: Options to pass down to the underlying urllib3 socket.
182
+ :param datetime_format: Datetime format string for serialization.
183
+ :param date_format: Date format string for serialization.
184
+
185
+ :Example:
186
+ """
187
+
188
+ _default: ClassVar[Optional[Self]] = None
189
+
190
+ def __init__(
191
+ self,
192
+ host: Optional[str]=None,
193
+ api_key: Optional[Dict[str, str]]=None,
194
+ api_key_prefix: Optional[Dict[str, str]]=None,
195
+ username: Optional[str]=None,
196
+ password: Optional[str]=None,
197
+ access_token: Optional[str]=None,
198
+ server_index: Optional[int]=None,
199
+ server_variables: Optional[ServerVariablesT]=None,
200
+ server_operation_index: Optional[Dict[int, int]]=None,
201
+ server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None,
202
+ ignore_operation_servers: bool=False,
203
+ ssl_ca_cert: Optional[str]=None,
204
+ retries: Optional[Union[int, urllib3.util.retry.Retry]] = None,
205
+ ca_cert_data: Optional[Union[str, bytes]] = None,
206
+ cert_file: Optional[str]=None,
207
+ key_file: Optional[str]=None,
208
+ verify_ssl: bool=True,
209
+ assert_hostname: Optional[bool]=None,
210
+ tls_server_name: Optional[str]=None,
211
+ connection_pool_maxsize: Optional[int]=None,
212
+ proxy: Optional[str]=None,
213
+ no_proxy: Optional[str]=None,
214
+ proxy_headers: Optional[Any]=None,
215
+ proxy_ssl_context: Optional[ssl.SSLContext]=None,
216
+ safe_chars_for_path_param: str='',
217
+ client_side_validation: bool=True,
218
+ socket_options: Optional[Any]=None,
219
+ datetime_format: str="%Y-%m-%dT%H:%M:%S.%f%z",
220
+ date_format: str="%Y-%m-%d",
221
+ *,
222
+ debug: Optional[bool] = None,
223
+ ) -> None:
224
+ """Constructor
225
+ """
226
+ self._base_path = "https://api.stract-api.com" if host is None else host
227
+ """Default Base url
228
+ """
229
+ self.server_index = 0 if server_index is None and host is None else server_index
230
+ self.server_operation_index = server_operation_index or {}
231
+ """Default server index
232
+ """
233
+ self.server_variables = server_variables or {}
234
+ self.server_operation_variables = server_operation_variables or {}
235
+ """Default server variables
236
+ """
237
+ self.ignore_operation_servers = ignore_operation_servers
238
+ """Ignore operation servers
239
+ """
240
+ self.temp_folder_path = None
241
+ """Temp file folder for downloading files
242
+ """
243
+ # Authentication Settings
244
+ self.api_key = {}
245
+ if api_key:
246
+ self.api_key = api_key
247
+ """dict to store API key(s)
248
+ """
249
+ self.api_key_prefix = {}
250
+ if api_key_prefix:
251
+ self.api_key_prefix = api_key_prefix
252
+ """dict to store API prefix (e.g. Bearer)
253
+ """
254
+ self.refresh_api_key_hook = None
255
+ """function hook to refresh API key if expired
256
+ """
257
+ self.username = username
258
+ """Username for HTTP basic authentication
259
+ """
260
+ self.password = password
261
+ """Password for HTTP basic authentication
262
+ """
263
+ self.access_token = access_token
264
+ """Access token
265
+ """
266
+ self.logger = {}
267
+ """Logging Settings
268
+ """
269
+ self.logger["package_logger"] = logging.getLogger("stract_api")
270
+ self.logger["urllib3_logger"] = logging.getLogger("urllib3")
271
+ self.logger_format = '%(asctime)s %(levelname)s %(message)s'
272
+ """Log format
273
+ """
274
+ self.logger_stream_handler = None
275
+ """Log stream handler
276
+ """
277
+ self.logger_file_handler: Optional[FileHandler] = None
278
+ """Log file handler
279
+ """
280
+ self.logger_file = None
281
+ """Debug file location
282
+ """
283
+ if debug is not None:
284
+ self.debug = debug
285
+ else:
286
+ self.__debug = False
287
+ """Debug switch
288
+ """
289
+
290
+ self.verify_ssl = verify_ssl
291
+ """SSL/TLS verification
292
+ Set this to false to skip verifying SSL certificate when calling API
293
+ from https server.
294
+ """
295
+ self.ssl_ca_cert = ssl_ca_cert
296
+ """Set this to customize the certificate file to verify the peer.
297
+ """
298
+ self.ca_cert_data = ca_cert_data
299
+ """Set this to verify the peer using PEM (str) or DER (bytes)
300
+ certificate data.
301
+ """
302
+ self.cert_file = cert_file
303
+ """client certificate file
304
+ """
305
+ self.key_file = key_file
306
+ """client key file
307
+ """
308
+ self.assert_hostname = assert_hostname
309
+ """Set this to True/False to enable/disable SSL hostname verification.
310
+ """
311
+ self.tls_server_name = tls_server_name
312
+ """SSL/TLS Server Name Indication (SNI)
313
+ Set this to the SNI value expected by the server.
314
+ """
315
+
316
+ self.connection_pool_maxsize = connection_pool_maxsize if connection_pool_maxsize is not None else multiprocessing.cpu_count() * 5
317
+ """urllib3 connection pool's maximum number of connections saved
318
+ per pool. None in the constructor is coerced to cpu_count * 5.
319
+ """
320
+
321
+ # urllib3 does not read proxy environment variables itself:
322
+ # https://github.com/urllib3/urllib3/issues/1785
323
+ # A proxy taken from the environment is re-resolved when the host is
324
+ # assigned; see the host setter.
325
+ self._proxy_from_env = proxy is None
326
+ if proxy is None or no_proxy is None:
327
+ proxies = getproxies()
328
+ if proxy is None:
329
+ proxy = self._env_proxy(proxies, self.host)
330
+ if no_proxy is None:
331
+ no_proxy = proxies.get("no")
332
+ self._proxy = proxy
333
+ self.no_proxy = no_proxy
334
+ """Hosts that bypass the proxy
335
+ """
336
+ self.proxy_headers = proxy_headers
337
+ """Proxy headers
338
+ """
339
+ self.proxy_ssl_context = proxy_ssl_context
340
+ """SSL context used only for the TLS handshake with the proxy itself
341
+ (e.g. an HTTPS CONNECT tunnel), independent of the destination TLS
342
+ settings above.
343
+ """
344
+ self.safe_chars_for_path_param = safe_chars_for_path_param
345
+ """Safe chars for path_param
346
+ """
347
+ self.retries = retries
348
+ """Retry configuration
349
+ """
350
+ # Enable client side validation
351
+ self.client_side_validation = client_side_validation
352
+
353
+ self.socket_options = socket_options
354
+ """Options to pass down to the underlying urllib3 socket
355
+ """
356
+
357
+ self.datetime_format = datetime_format
358
+ """datetime format
359
+ """
360
+
361
+ self.date_format = date_format
362
+ """date format
363
+ """
364
+
365
+ def __deepcopy__(self, memo: Dict[int, Any]) -> Self:
366
+ cls = self.__class__
367
+ result = cls.__new__(cls)
368
+ memo[id(self)] = result
369
+ for k, v in self.__dict__.items():
370
+ if k == 'proxy_ssl_context':
371
+ # ssl.SSLContext holds unpicklable C state and can't be deepcopied.
372
+ setattr(result, k, v)
373
+ continue
374
+ if k not in ('logger', 'logger_file_handler'):
375
+ setattr(result, k, copy.deepcopy(v, memo))
376
+ # shallow copy of loggers
377
+ result.logger = copy.copy(self.logger)
378
+ # use setter to re-create the file handler (excluded from __dict__ copy)
379
+ result.logger_file = self.logger_file
380
+
381
+ return result
382
+
383
+ def __setattr__(self, name: str, value: Any) -> None:
384
+ object.__setattr__(self, name, value)
385
+
386
+ @classmethod
387
+ def set_default(cls, default: Optional[Self]) -> None:
388
+ """Set default instance of configuration.
389
+
390
+ It stores default configuration, which can be
391
+ returned by get_default_copy method.
392
+
393
+ :param default: object of Configuration
394
+ """
395
+ cls._default = default
396
+
397
+ @classmethod
398
+ def get_default_copy(cls) -> Self:
399
+ """Deprecated. Please use `get_default` instead.
400
+
401
+ Deprecated. Please use `get_default` instead.
402
+
403
+ :return: The configuration object.
404
+ """
405
+ return cls.get_default()
406
+
407
+ @classmethod
408
+ def get_default(cls) -> Self:
409
+ """Return the default configuration.
410
+
411
+ This method returns newly created, based on default constructor,
412
+ object of Configuration class or returns a copy of default
413
+ configuration.
414
+
415
+ :return: The configuration object.
416
+ """
417
+ if cls._default is None:
418
+ cls._default = cls()
419
+ return cls._default
420
+
421
+ @property
422
+ def logger_file(self) -> Optional[str]:
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
+ return self.__logger_file
432
+
433
+ @logger_file.setter
434
+ def logger_file(self, value: Optional[str]) -> None:
435
+ """The logger file.
436
+
437
+ If the logger_file is None, then add stream handler and remove file
438
+ handler. Otherwise, add file handler and remove stream handler.
439
+
440
+ :param value: The logger_file path.
441
+ :type: str
442
+ """
443
+ self.__logger_file = value
444
+ if self.__logger_file:
445
+ # If set logging file,
446
+ # then add file handler and remove stream handler.
447
+ self.logger_file_handler = logging.FileHandler(self.__logger_file)
448
+ self.logger_file_handler.setFormatter(self.logger_formatter)
449
+ for _, logger in self.logger.items():
450
+ logger.addHandler(self.logger_file_handler)
451
+
452
+ @property
453
+ def debug(self) -> bool:
454
+ """Debug status
455
+
456
+ :param value: The debug status, True or False.
457
+ :type: bool
458
+ """
459
+ return self.__debug
460
+
461
+ @debug.setter
462
+ def debug(self, value: bool) -> None:
463
+ """Debug status
464
+
465
+ :param value: The debug status, True or False.
466
+ :type: bool
467
+ """
468
+ self.__debug = value
469
+ if self.__debug:
470
+ # if debug status is True, turn on debug logging
471
+ for _, logger in self.logger.items():
472
+ logger.setLevel(logging.DEBUG)
473
+ # turn on httplib debug
474
+ httplib.HTTPConnection.debuglevel = 1
475
+ else:
476
+ # if debug status is False, turn off debug logging,
477
+ # setting log level to default `logging.WARNING`
478
+ for _, logger in self.logger.items():
479
+ logger.setLevel(logging.WARNING)
480
+ # turn off httplib debug
481
+ httplib.HTTPConnection.debuglevel = 0
482
+
483
+ @property
484
+ def logger_format(self) -> str:
485
+ """The logger format.
486
+
487
+ The logger_formatter will be updated when sets logger_format.
488
+
489
+ :param value: The format string.
490
+ :type: str
491
+ """
492
+ return self.__logger_format
493
+
494
+ @logger_format.setter
495
+ def logger_format(self, value: str) -> None:
496
+ """The logger format.
497
+
498
+ The logger_formatter will be updated when sets logger_format.
499
+
500
+ :param value: The format string.
501
+ :type: str
502
+ """
503
+ self.__logger_format = value
504
+ self.logger_formatter = logging.Formatter(self.__logger_format)
505
+
506
+ def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]:
507
+ """Gets API key (with prefix if set).
508
+
509
+ :param identifier: The identifier of apiKey.
510
+ :param alias: The alternative identifier of apiKey.
511
+ :return: The token for api key authentication.
512
+ """
513
+ if self.refresh_api_key_hook is not None:
514
+ self.refresh_api_key_hook(self)
515
+ key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None)
516
+ if key:
517
+ prefix = self.api_key_prefix.get(
518
+ identifier, self.api_key_prefix.get(alias) if alias is not None else None)
519
+ if prefix:
520
+ return "%s %s" % (prefix, key)
521
+ else:
522
+ return key
523
+
524
+ return None
525
+
526
+ def get_basic_auth_token(self) -> Optional[str]:
527
+ """Gets HTTP basic authentication header (string).
528
+
529
+ :return: The token for basic HTTP authentication.
530
+ """
531
+ username = ""
532
+ if self.username is not None:
533
+ username = self.username
534
+ password = ""
535
+ if self.password is not None:
536
+ password = self.password
537
+
538
+ return urllib3.util.make_headers(
539
+ basic_auth=username + ':' + password
540
+ ).get('authorization')
541
+
542
+ def auth_settings(self)-> AuthSettings:
543
+ """Gets Auth Settings dict for api client.
544
+
545
+ :return: The Auth Settings information dict.
546
+ """
547
+ auth: AuthSettings = {}
548
+ if self.access_token is not None:
549
+ auth['bearerAuth'] = {
550
+ 'type': 'bearer',
551
+ 'in': 'header',
552
+ 'key': 'Authorization',
553
+ 'value': 'Bearer ' + self.access_token
554
+ }
555
+ return auth
556
+
557
+ def to_debug_report(self) -> str:
558
+ """Gets the essential information for debugging.
559
+
560
+ :return: The report for debugging.
561
+ """
562
+ return "Python SDK Debug Report:\n"\
563
+ "OS: {env}\n"\
564
+ "Python Version: {pyversion}\n"\
565
+ "Version of the API: 0.9.4\n"\
566
+ "SDK Package Version: 0.1.0".\
567
+ format(env=sys.platform, pyversion=sys.version)
568
+
569
+ def get_host_settings(self) -> List[HostSetting]:
570
+ """Gets an array of host settings
571
+
572
+ :return: An array of host settings
573
+ """
574
+ return [
575
+ {
576
+ 'url': "https://api.stract-api.com",
577
+ 'description': "Production",
578
+ }
579
+ ]
580
+
581
+ def get_host_from_settings(
582
+ self,
583
+ index: Optional[int],
584
+ variables: Optional[ServerVariablesT]=None,
585
+ servers: Optional[List[HostSetting]]=None,
586
+ ) -> str:
587
+ """Gets host URL based on the index and variables
588
+ :param index: array index of the host settings
589
+ :param variables: hash of variable and the corresponding value
590
+ :param servers: an array of host settings or None
591
+ :return: URL based on host settings
592
+ """
593
+ if index is None:
594
+ return self._base_path
595
+
596
+ variables = {} if variables is None else variables
597
+ servers = self.get_host_settings() if servers is None else servers
598
+
599
+ try:
600
+ server = servers[index]
601
+ except IndexError:
602
+ raise ValueError(
603
+ "Invalid index {0} when selecting the host settings. "
604
+ "Must be less than {1}".format(index, len(servers)))
605
+
606
+ url = server['url']
607
+
608
+ # go through variables and replace placeholders
609
+ for variable_name, variable in server.get('variables', {}).items():
610
+ used_value = variables.get(
611
+ variable_name, variable['default_value'])
612
+
613
+ if 'enum_values' in variable \
614
+ and variable['enum_values'] \
615
+ and used_value not in variable['enum_values']:
616
+ raise ValueError(
617
+ "The variable `{0}` in the host URL has invalid value "
618
+ "{1}. Must be {2}.".format(
619
+ variable_name, variables[variable_name],
620
+ variable['enum_values']))
621
+
622
+ url = url.replace("{" + variable_name + "}", used_value)
623
+
624
+ return url
625
+
626
+ @property
627
+ def host(self) -> str:
628
+ """Return generated host."""
629
+ return self.get_host_from_settings(self.server_index, variables=self.server_variables)
630
+
631
+ @host.setter
632
+ def host(self, value: str) -> None:
633
+ """Fix base path."""
634
+ self._base_path = value
635
+ self.server_index = None
636
+ if self._proxy_from_env:
637
+ # the scheme-specific proxy depends on the host, which is
638
+ # commonly assigned after construction
639
+ self._proxy = self._env_proxy(getproxies(), value)
640
+
641
+ @staticmethod
642
+ def _env_proxy(proxies: Dict[str, str], host: str) -> Optional[str]:
643
+ """Pick the environment proxy that applies to `host`."""
644
+ return proxies.get(urlparse(host).scheme) or proxies.get("all")
645
+
646
+ @property
647
+ def proxy(self) -> Optional[str]:
648
+ """Proxy URL
649
+ """
650
+ return self._proxy
651
+
652
+ @proxy.setter
653
+ def proxy(self, value: Optional[str]) -> None:
654
+ self._proxy = value
655
+ self._proxy_from_env = False