opportify-sdk 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 (49) hide show
  1. lib/__init__.py +0 -0
  2. lib/v1/__init__.py +0 -0
  3. lib/v1/openapi_client/__init__.py +63 -0
  4. lib/v1/openapi_client/api/__init__.py +6 -0
  5. lib/v1/openapi_client/api/email_insights_api.py +317 -0
  6. lib/v1/openapi_client/api/ip_insights_api.py +322 -0
  7. lib/v1/openapi_client/api_client.py +797 -0
  8. lib/v1/openapi_client/api_response.py +21 -0
  9. lib/v1/openapi_client/configuration.py +595 -0
  10. lib/v1/openapi_client/exceptions.py +199 -0
  11. lib/v1/openapi_client/models/__init__.py +45 -0
  12. lib/v1/openapi_client/models/abuse_contact.py +99 -0
  13. lib/v1/openapi_client/models/admin_contact.py +99 -0
  14. lib/v1/openapi_client/models/analyze_email200_response.py +113 -0
  15. lib/v1/openapi_client/models/analyze_email400_response.py +91 -0
  16. lib/v1/openapi_client/models/analyze_email400_response_error.py +137 -0
  17. lib/v1/openapi_client/models/analyze_email500_response.py +91 -0
  18. lib/v1/openapi_client/models/analyze_email500_response_error.py +89 -0
  19. lib/v1/openapi_client/models/analyze_email_request.py +92 -0
  20. lib/v1/openapi_client/models/analyze_ip200_response.py +127 -0
  21. lib/v1/openapi_client/models/analyze_ip400_response.py +91 -0
  22. lib/v1/openapi_client/models/analyze_ip400_response_error.py +137 -0
  23. lib/v1/openapi_client/models/analyze_ip404_response.py +91 -0
  24. lib/v1/openapi_client/models/analyze_ip500_response.py +91 -0
  25. lib/v1/openapi_client/models/analyze_ip_request.py +89 -0
  26. lib/v1/openapi_client/models/asn.py +93 -0
  27. lib/v1/openapi_client/models/block_listed.py +94 -0
  28. lib/v1/openapi_client/models/email_dns.py +87 -0
  29. lib/v1/openapi_client/models/geo.py +113 -0
  30. lib/v1/openapi_client/models/internalerror.py +89 -0
  31. lib/v1/openapi_client/models/invalidemail.py +89 -0
  32. lib/v1/openapi_client/models/ipvalidationfailed.py +89 -0
  33. lib/v1/openapi_client/models/malformedrequest.py +89 -0
  34. lib/v1/openapi_client/models/malformedrequest1.py +89 -0
  35. lib/v1/openapi_client/models/notfound.py +89 -0
  36. lib/v1/openapi_client/models/organization.py +103 -0
  37. lib/v1/openapi_client/models/risk_report.py +89 -0
  38. lib/v1/openapi_client/models/tech_contact.py +99 -0
  39. lib/v1/openapi_client/models/trusted_provider.py +93 -0
  40. lib/v1/openapi_client/models/whois.py +117 -0
  41. lib/v1/openapi_client/py.typed +0 -0
  42. lib/v1/openapi_client/rest.py +257 -0
  43. opportify_sdk-0.1.0.dist-info/METADATA +16 -0
  44. opportify_sdk-0.1.0.dist-info/RECORD +49 -0
  45. opportify_sdk-0.1.0.dist-info/WHEEL +5 -0
  46. opportify_sdk-0.1.0.dist-info/top_level.txt +2 -0
  47. src/__init__.py +6 -0
  48. src/email_insights.py +97 -0
  49. src/ip_insights.py +93 -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,595 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Opportify Insights API
5
+
6
+ ## Overview The **Opportify Insights API** provides access to a powerful and up-to-date platform. With advanced data warehousing and AI-driven capabilities, this API is designed to empower your business to make informed, data-driven decisions and effectively assess potential risks. ### Base URL Use the following base URL for all API requests: ```plaintext https://api.opportify.ai/insights/v1/<service>/<endpoint> ``` ### Features - [**Email Insights:**](/docs/api-reference/email-insights) - Validate email syntax. - Identify email types (free, disposable, corporate or unknown). - Real time verifications: - Reachable: Confirms if the email domain has valid MX DNS records using DNS lookup. - Deliverable: Simulates an SMTP handshake to check if the email address exists and is deliverable. - Catch-All: Detects if the domain accepts all emails (catch-all configuration). - Intelligent Error Correction: Automatically corrects well-known misspelled email addresses. - Risk Report: Provides an AI-driven normalized score (200-1000) to evaluate email risk, using predefined thresholds. [Access Documentation >>](/docs/api-reference/email-insights) - [**IP Insights:**](/docs/api-reference/ip-insights) - Connection types: Detects connection types such as `wired`, `mobile`, `enterprise`, `satellite`, `VPN`, `cloud-provider`, `open-proxy`, or `Tor`. - Geo location: Delivers detailed insights such as country, city, timezone, language preferences, and additional location-based information to enhance regional understanding. - WHOIS: Provides main details including RIR, ASN, organization, and abuse/admin/technical contacts. - Trusted Provider Recognition: Identifies if the IP is part of a known trusted provider (e.g., ZTNA - Zero Trust Network Access). - Blocklist Reports: Retrieves up-to-date blocklist statuses, active reports, and the latest detections. - Risk Report: Delivers an AI-driven normalized score (200-1000) to evaluate IP risk, supported by predefined thresholds. [Access Documentation >>](/docs/api-reference/ip-insights) ### Authentication & Security - **API Key:** Access to the API requires an API key, which must be included in the request headers. Businesses can generate unlimited API keys directly from their account, offering flexibility and ease of use. - **ACL Rules:** Enhance security with Access Control Lists (ACL), allowing you to restrict API access from specific IP addresses or ranges. This feature provides an additional layer of protection by ensuring only authorized IPs can interact with the API. - **No Query Parameters:** As a precautionary measure, our API avoids the use of query parameters for all operations, including authentication and handling Personally Identifiable Information (PII). This approach minimizes security risks by preventing sensitive data from being exposed in access logs, browser history, cached URLs, debugging tools, or inadvertently shared URLs. All sensitive information is securely transmitted through headers or the request body.
7
+
8
+ The version of the OpenAPI document: 1.0.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
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
+ "opportifyToken": APIKeyAuthSetting,
117
+ },
118
+ total=False,
119
+ )
120
+
121
+
122
+ class HostSettingVariable(TypedDict):
123
+ description: str
124
+ default_value: str
125
+ enum_values: List[str]
126
+
127
+
128
+ class HostSetting(TypedDict):
129
+ url: str
130
+ description: str
131
+ variables: NotRequired[Dict[str, HostSettingVariable]]
132
+
133
+
134
+ class Configuration:
135
+ """This class contains various settings of the API client.
136
+
137
+ :param host: Base url.
138
+ :param ignore_operation_servers
139
+ Boolean to ignore operation servers for the API client.
140
+ Config will use `host` as the base url regardless of the operation servers.
141
+ :param api_key: Dict to store API key(s).
142
+ Each entry in the dict specifies an API key.
143
+ The dict key is the name of the security scheme in the OAS specification.
144
+ The dict value is the API key secret.
145
+ :param api_key_prefix: Dict to store API prefix (e.g. Bearer).
146
+ The dict key is the name of the security scheme in the OAS specification.
147
+ The dict value is an API key prefix when generating the auth data.
148
+ :param username: Username for HTTP basic authentication.
149
+ :param password: Password for HTTP basic authentication.
150
+ :param access_token: Access token.
151
+ :param server_index: Index to servers configuration.
152
+ :param server_variables: Mapping with string values to replace variables in
153
+ templated server configuration. The validation of enums is performed for
154
+ variables with defined enum values before.
155
+ :param server_operation_index: Mapping from operation ID to an index to server
156
+ configuration.
157
+ :param server_operation_variables: Mapping from operation ID to a mapping with
158
+ string values to replace variables in templated server configuration.
159
+ The validation of enums is performed for variables with defined enum
160
+ values before.
161
+ :param ssl_ca_cert: str - the path to a file of concatenated CA certificates
162
+ in PEM format.
163
+ :param retries: Number of retries for API requests.
164
+
165
+ :Example:
166
+
167
+ API Key Authentication Example.
168
+ Given the following security scheme in the OpenAPI specification:
169
+ components:
170
+ securitySchemes:
171
+ cookieAuth: # name for the security scheme
172
+ type: apiKey
173
+ in: cookie
174
+ name: JSESSIONID # cookie name
175
+
176
+ You can programmatically set the cookie:
177
+
178
+ conf = openapi_client.Configuration(
179
+ api_key={'cookieAuth': 'abc123'}
180
+ api_key_prefix={'cookieAuth': 'JSESSIONID'}
181
+ )
182
+
183
+ The following cookie will be added to the HTTP request:
184
+ Cookie: JSESSIONID abc123
185
+ """
186
+
187
+ _default: ClassVar[Optional[Self]] = None
188
+
189
+ def __init__(
190
+ self,
191
+ host: Optional[str]=None,
192
+ api_key: Optional[Dict[str, str]]=None,
193
+ api_key_prefix: Optional[Dict[str, str]]=None,
194
+ username: Optional[str]=None,
195
+ password: Optional[str]=None,
196
+ access_token: Optional[str]=None,
197
+ server_index: Optional[int]=None,
198
+ server_variables: Optional[ServerVariablesT]=None,
199
+ server_operation_index: Optional[Dict[int, int]]=None,
200
+ server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None,
201
+ ignore_operation_servers: bool=False,
202
+ ssl_ca_cert: Optional[str]=None,
203
+ retries: Optional[int] = None,
204
+ *,
205
+ debug: Optional[bool] = None,
206
+ ) -> None:
207
+ """Constructor
208
+ """
209
+ self._base_path = "https://api.opportify.ai/insights/v1" if host is None else host
210
+ """Default Base url
211
+ """
212
+ self.server_index = 0 if server_index is None and host is None else server_index
213
+ self.server_operation_index = server_operation_index or {}
214
+ """Default server index
215
+ """
216
+ self.server_variables = server_variables or {}
217
+ self.server_operation_variables = server_operation_variables or {}
218
+ """Default server variables
219
+ """
220
+ self.ignore_operation_servers = ignore_operation_servers
221
+ """Ignore operation servers
222
+ """
223
+ self.temp_folder_path = None
224
+ """Temp file folder for downloading files
225
+ """
226
+ # Authentication Settings
227
+ self.api_key = {}
228
+ if api_key:
229
+ self.api_key = api_key
230
+ """dict to store API key(s)
231
+ """
232
+ self.api_key_prefix = {}
233
+ if api_key_prefix:
234
+ self.api_key_prefix = api_key_prefix
235
+ """dict to store API prefix (e.g. Bearer)
236
+ """
237
+ self.refresh_api_key_hook = None
238
+ """function hook to refresh API key if expired
239
+ """
240
+ self.username = username
241
+ """Username for HTTP basic authentication
242
+ """
243
+ self.password = password
244
+ """Password for HTTP basic authentication
245
+ """
246
+ self.access_token = access_token
247
+ """Access token
248
+ """
249
+ self.logger = {}
250
+ """Logging Settings
251
+ """
252
+ self.logger["package_logger"] = logging.getLogger("openapi_client")
253
+ self.logger["urllib3_logger"] = logging.getLogger("urllib3")
254
+ self.logger_format = '%(asctime)s %(levelname)s %(message)s'
255
+ """Log format
256
+ """
257
+ self.logger_stream_handler = None
258
+ """Log stream handler
259
+ """
260
+ self.logger_file_handler: Optional[FileHandler] = None
261
+ """Log file handler
262
+ """
263
+ self.logger_file = None
264
+ """Debug file location
265
+ """
266
+ if debug is not None:
267
+ self.debug = debug
268
+ else:
269
+ self.__debug = False
270
+ """Debug switch
271
+ """
272
+
273
+ self.verify_ssl = True
274
+ """SSL/TLS verification
275
+ Set this to false to skip verifying SSL certificate when calling API
276
+ from https server.
277
+ """
278
+ self.ssl_ca_cert = ssl_ca_cert
279
+ """Set this to customize the certificate file to verify the peer.
280
+ """
281
+ self.cert_file = None
282
+ """client certificate file
283
+ """
284
+ self.key_file = None
285
+ """client key file
286
+ """
287
+ self.assert_hostname = None
288
+ """Set this to True/False to enable/disable SSL hostname verification.
289
+ """
290
+ self.tls_server_name = None
291
+ """SSL/TLS Server Name Indication (SNI)
292
+ Set this to the SNI value expected by the server.
293
+ """
294
+
295
+ self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
296
+ """urllib3 connection pool's maximum number of connections saved
297
+ per pool. urllib3 uses 1 connection as default value, but this is
298
+ not the best value when you are making a lot of possibly parallel
299
+ requests to the same host, which is often the case here.
300
+ cpu_count * 5 is used as default value to increase performance.
301
+ """
302
+
303
+ self.proxy: Optional[str] = None
304
+ """Proxy URL
305
+ """
306
+ self.proxy_headers = None
307
+ """Proxy headers
308
+ """
309
+ self.safe_chars_for_path_param = ''
310
+ """Safe chars for path_param
311
+ """
312
+ self.retries = retries
313
+ """Adding retries to override urllib3 default value 3
314
+ """
315
+ # Enable client side validation
316
+ self.client_side_validation = True
317
+
318
+ self.socket_options = None
319
+ """Options to pass down to the underlying urllib3 socket
320
+ """
321
+
322
+ self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z"
323
+ """datetime format
324
+ """
325
+
326
+ self.date_format = "%Y-%m-%d"
327
+ """date format
328
+ """
329
+
330
+ def __deepcopy__(self, memo: Dict[int, Any]) -> Self:
331
+ cls = self.__class__
332
+ result = cls.__new__(cls)
333
+ memo[id(self)] = result
334
+ for k, v in self.__dict__.items():
335
+ if k not in ('logger', 'logger_file_handler'):
336
+ setattr(result, k, copy.deepcopy(v, memo))
337
+ # shallow copy of loggers
338
+ result.logger = copy.copy(self.logger)
339
+ # use setters to configure loggers
340
+ result.logger_file = self.logger_file
341
+ result.debug = self.debug
342
+ return result
343
+
344
+ def __setattr__(self, name: str, value: Any) -> None:
345
+ object.__setattr__(self, name, value)
346
+
347
+ @classmethod
348
+ def set_default(cls, default: Optional[Self]) -> None:
349
+ """Set default instance of configuration.
350
+
351
+ It stores default configuration, which can be
352
+ returned by get_default_copy method.
353
+
354
+ :param default: object of Configuration
355
+ """
356
+ cls._default = default
357
+
358
+ @classmethod
359
+ def get_default_copy(cls) -> Self:
360
+ """Deprecated. Please use `get_default` instead.
361
+
362
+ Deprecated. Please use `get_default` instead.
363
+
364
+ :return: The configuration object.
365
+ """
366
+ return cls.get_default()
367
+
368
+ @classmethod
369
+ def get_default(cls) -> Self:
370
+ """Return the default configuration.
371
+
372
+ This method returns newly created, based on default constructor,
373
+ object of Configuration class or returns a copy of default
374
+ configuration.
375
+
376
+ :return: The configuration object.
377
+ """
378
+ if cls._default is None:
379
+ cls._default = cls()
380
+ return cls._default
381
+
382
+ @property
383
+ def logger_file(self) -> Optional[str]:
384
+ """The logger file.
385
+
386
+ If the logger_file is None, then add stream handler and remove file
387
+ handler. Otherwise, add file handler and remove stream handler.
388
+
389
+ :param value: The logger_file path.
390
+ :type: str
391
+ """
392
+ return self.__logger_file
393
+
394
+ @logger_file.setter
395
+ def logger_file(self, value: Optional[str]) -> None:
396
+ """The logger file.
397
+
398
+ If the logger_file is None, then add stream handler and remove file
399
+ handler. Otherwise, add file handler and remove stream handler.
400
+
401
+ :param value: The logger_file path.
402
+ :type: str
403
+ """
404
+ self.__logger_file = value
405
+ if self.__logger_file:
406
+ # If set logging file,
407
+ # then add file handler and remove stream handler.
408
+ self.logger_file_handler = logging.FileHandler(self.__logger_file)
409
+ self.logger_file_handler.setFormatter(self.logger_formatter)
410
+ for _, logger in self.logger.items():
411
+ logger.addHandler(self.logger_file_handler)
412
+
413
+ @property
414
+ def debug(self) -> bool:
415
+ """Debug status
416
+
417
+ :param value: The debug status, True or False.
418
+ :type: bool
419
+ """
420
+ return self.__debug
421
+
422
+ @debug.setter
423
+ def debug(self, value: bool) -> None:
424
+ """Debug status
425
+
426
+ :param value: The debug status, True or False.
427
+ :type: bool
428
+ """
429
+ self.__debug = value
430
+ if self.__debug:
431
+ # if debug status is True, turn on debug logging
432
+ for _, logger in self.logger.items():
433
+ logger.setLevel(logging.DEBUG)
434
+ # turn on httplib debug
435
+ httplib.HTTPConnection.debuglevel = 1
436
+ else:
437
+ # if debug status is False, turn off debug logging,
438
+ # setting log level to default `logging.WARNING`
439
+ for _, logger in self.logger.items():
440
+ logger.setLevel(logging.WARNING)
441
+ # turn off httplib debug
442
+ httplib.HTTPConnection.debuglevel = 0
443
+
444
+ @property
445
+ def logger_format(self) -> str:
446
+ """The logger format.
447
+
448
+ The logger_formatter will be updated when sets logger_format.
449
+
450
+ :param value: The format string.
451
+ :type: str
452
+ """
453
+ return self.__logger_format
454
+
455
+ @logger_format.setter
456
+ def logger_format(self, value: str) -> None:
457
+ """The logger format.
458
+
459
+ The logger_formatter will be updated when sets logger_format.
460
+
461
+ :param value: The format string.
462
+ :type: str
463
+ """
464
+ self.__logger_format = value
465
+ self.logger_formatter = logging.Formatter(self.__logger_format)
466
+
467
+ def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]:
468
+ """Gets API key (with prefix if set).
469
+
470
+ :param identifier: The identifier of apiKey.
471
+ :param alias: The alternative identifier of apiKey.
472
+ :return: The token for api key authentication.
473
+ """
474
+ if self.refresh_api_key_hook is not None:
475
+ self.refresh_api_key_hook(self)
476
+ key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None)
477
+ if key:
478
+ prefix = self.api_key_prefix.get(identifier)
479
+ if prefix:
480
+ return "%s %s" % (prefix, key)
481
+ else:
482
+ return key
483
+
484
+ return None
485
+
486
+ def get_basic_auth_token(self) -> Optional[str]:
487
+ """Gets HTTP basic authentication header (string).
488
+
489
+ :return: The token for basic HTTP authentication.
490
+ """
491
+ username = ""
492
+ if self.username is not None:
493
+ username = self.username
494
+ password = ""
495
+ if self.password is not None:
496
+ password = self.password
497
+ return urllib3.util.make_headers(
498
+ basic_auth=username + ':' + password
499
+ ).get('authorization')
500
+
501
+ def auth_settings(self)-> AuthSettings:
502
+ """Gets Auth Settings dict for api client.
503
+
504
+ :return: The Auth Settings information dict.
505
+ """
506
+ auth: AuthSettings = {}
507
+ if 'opportifyToken' in self.api_key:
508
+ auth['opportifyToken'] = {
509
+ 'type': 'api_key',
510
+ 'in': 'header',
511
+ 'key': 'x-opportify-token',
512
+ 'value': self.get_api_key_with_prefix(
513
+ 'opportifyToken',
514
+ ),
515
+ }
516
+ return auth
517
+
518
+ def to_debug_report(self) -> str:
519
+ """Gets the essential information for debugging.
520
+
521
+ :return: The report for debugging.
522
+ """
523
+ return "Python SDK Debug Report:\n"\
524
+ "OS: {env}\n"\
525
+ "Python Version: {pyversion}\n"\
526
+ "Version of the API: 1.0.0\n"\
527
+ "SDK Package Version: 1.0.0".\
528
+ format(env=sys.platform, pyversion=sys.version)
529
+
530
+ def get_host_settings(self) -> List[HostSetting]:
531
+ """Gets an array of host settings
532
+
533
+ :return: An array of host settings
534
+ """
535
+ return [
536
+ {
537
+ 'url': "https://api.opportify.ai/insights/v1",
538
+ 'description': "Production server",
539
+ }
540
+ ]
541
+
542
+ def get_host_from_settings(
543
+ self,
544
+ index: Optional[int],
545
+ variables: Optional[ServerVariablesT]=None,
546
+ servers: Optional[List[HostSetting]]=None,
547
+ ) -> str:
548
+ """Gets host URL based on the index and variables
549
+ :param index: array index of the host settings
550
+ :param variables: hash of variable and the corresponding value
551
+ :param servers: an array of host settings or None
552
+ :return: URL based on host settings
553
+ """
554
+ if index is None:
555
+ return self._base_path
556
+
557
+ variables = {} if variables is None else variables
558
+ servers = self.get_host_settings() if servers is None else servers
559
+
560
+ try:
561
+ server = servers[index]
562
+ except IndexError:
563
+ raise ValueError(
564
+ "Invalid index {0} when selecting the host settings. "
565
+ "Must be less than {1}".format(index, len(servers)))
566
+
567
+ url = server['url']
568
+
569
+ # go through variables and replace placeholders
570
+ for variable_name, variable in server.get('variables', {}).items():
571
+ used_value = variables.get(
572
+ variable_name, variable['default_value'])
573
+
574
+ if 'enum_values' in variable \
575
+ and used_value not in variable['enum_values']:
576
+ raise ValueError(
577
+ "The variable `{0}` in the host URL has invalid value "
578
+ "{1}. Must be {2}.".format(
579
+ variable_name, variables[variable_name],
580
+ variable['enum_values']))
581
+
582
+ url = url.replace("{" + variable_name + "}", used_value)
583
+
584
+ return url
585
+
586
+ @property
587
+ def host(self) -> str:
588
+ """Return generated host."""
589
+ return self.get_host_from_settings(self.server_index, variables=self.server_variables)
590
+
591
+ @host.setter
592
+ def host(self, value: str) -> None:
593
+ """Fix base path."""
594
+ self._base_path = value
595
+ self.server_index = None