vectorize_client.configuration

Vectorize API

API for Vectorize services (Beta)

The version of the OpenAPI document: 0.1.2 Generated by OpenAPI Generator (https://openapi-generator.tech)

Do not edit the class manually.

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

This class contains various settings of the API client.

Parameters
  • host: Base url. :param ignore_operation_servers Boolean to ignore operation servers for the API client. Config will use host as the base url regardless of the operation servers.
  • api_key: Dict to store API key(s). Each entry in the dict specifies an API key. The dict key is the name of the security scheme in the OAS specification. The dict value is the API key secret.
  • api_key_prefix: Dict to store API prefix (e.g. Bearer). The dict key is the name of the security scheme in the OAS specification. The dict value is an API key prefix when generating the auth data.
  • username: Username for HTTP basic authentication.
  • password: Password for HTTP basic authentication.
  • access_token: Access token.
  • server_index: Index to servers configuration.
  • server_variables: Mapping with string values to replace variables in templated server configuration. The validation of enums is performed for variables with defined enum values before.
  • server_operation_index: Mapping from operation ID to an index to server configuration.
  • server_operation_variables: Mapping from operation ID to a mapping with string values to replace variables in templated server configuration. The validation of enums is performed for variables with defined enum values before.
  • ssl_ca_cert: str - the path to a file of concatenated CA certificates in PEM format.
  • retries: Number of retries for API requests.
  • ca_cert_data: verify the peer using concatenated CA certificate data in PEM (str) or DER (bytes) format.

:Example:

Configuration( host: Optional[str] = None, api_key: Optional[Dict[str, str]] = None, api_key_prefix: Optional[Dict[str, str]] = None, username: Optional[str] = None, password: Optional[str] = None, access_token: Optional[str] = None, server_index: Optional[int] = None, server_variables: Optional[Dict[str, str]] = None, server_operation_index: Optional[Dict[int, int]] = None, server_operation_variables: Optional[Dict[int, Dict[str, str]]] = None, ignore_operation_servers: bool = False, ssl_ca_cert: Optional[str] = None, retries: Optional[int] = None, ca_cert_data: Union[str, bytes, NoneType] = None, *, debug: Optional[bool] = None)
173    def __init__(
174        self,
175        host: Optional[str]=None,
176        api_key: Optional[Dict[str, str]]=None,
177        api_key_prefix: Optional[Dict[str, str]]=None,
178        username: Optional[str]=None,
179        password: Optional[str]=None,
180        access_token: Optional[str]=None,
181        server_index: Optional[int]=None,
182        server_variables: Optional[ServerVariablesT]=None,
183        server_operation_index: Optional[Dict[int, int]]=None,
184        server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None,
185        ignore_operation_servers: bool=False,
186        ssl_ca_cert: Optional[str]=None,
187        retries: Optional[int] = None,
188        ca_cert_data: Optional[Union[str, bytes]] = None,
189        *,
190        debug: Optional[bool] = None,
191    ) -> None:
192        """Constructor
193        """
194        self._base_path = "https://api.vectorize.io/v1" if host is None else host
195        """Default Base url
196        """
197        self.server_index = 0 if server_index is None and host is None else server_index
198        self.server_operation_index = server_operation_index or {}
199        """Default server index
200        """
201        self.server_variables = server_variables or {}
202        self.server_operation_variables = server_operation_variables or {}
203        """Default server variables
204        """
205        self.ignore_operation_servers = ignore_operation_servers
206        """Ignore operation servers
207        """
208        self.temp_folder_path = None
209        """Temp file folder for downloading files
210        """
211        # Authentication Settings
212        self.api_key = {}
213        if api_key:
214            self.api_key = api_key
215        """dict to store API key(s)
216        """
217        self.api_key_prefix = {}
218        if api_key_prefix:
219            self.api_key_prefix = api_key_prefix
220        """dict to store API prefix (e.g. Bearer)
221        """
222        self.refresh_api_key_hook = None
223        """function hook to refresh API key if expired
224        """
225        self.username = username
226        """Username for HTTP basic authentication
227        """
228        self.password = password
229        """Password for HTTP basic authentication
230        """
231        self.access_token = access_token
232        """Access token
233        """
234        self.logger = {}
235        """Logging Settings
236        """
237        self.logger["package_logger"] = logging.getLogger("vectorize_client")
238        self.logger["urllib3_logger"] = logging.getLogger("urllib3")
239        self.logger_format = '%(asctime)s %(levelname)s %(message)s'
240        """Log format
241        """
242        self.logger_stream_handler = None
243        """Log stream handler
244        """
245        self.logger_file_handler: Optional[FileHandler] = None
246        """Log file handler
247        """
248        self.logger_file = None
249        """Debug file location
250        """
251        if debug is not None:
252            self.debug = debug
253        else:
254            self.__debug = False
255        """Debug switch
256        """
257
258        self.verify_ssl = True
259        """SSL/TLS verification
260           Set this to false to skip verifying SSL certificate when calling API
261           from https server.
262        """
263        self.ssl_ca_cert = ssl_ca_cert
264        """Set this to customize the certificate file to verify the peer.
265        """
266        self.ca_cert_data = ca_cert_data
267        """Set this to verify the peer using PEM (str) or DER (bytes)
268           certificate data.
269        """
270        self.cert_file = None
271        """client certificate file
272        """
273        self.key_file = None
274        """client key file
275        """
276        self.assert_hostname = None
277        """Set this to True/False to enable/disable SSL hostname verification.
278        """
279        self.tls_server_name = None
280        """SSL/TLS Server Name Indication (SNI)
281           Set this to the SNI value expected by the server.
282        """
283
284        self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
285        """urllib3 connection pool's maximum number of connections saved
286           per pool. urllib3 uses 1 connection as default value, but this is
287           not the best value when you are making a lot of possibly parallel
288           requests to the same host, which is often the case here.
289           cpu_count * 5 is used as default value to increase performance.
290        """
291
292        self.proxy: Optional[str] = None
293        """Proxy URL
294        """
295        self.proxy_headers = None
296        """Proxy headers
297        """
298        self.safe_chars_for_path_param = ''
299        """Safe chars for path_param
300        """
301        self.retries = retries
302        """Adding retries to override urllib3 default value 3
303        """
304        # Enable client side validation
305        self.client_side_validation = True
306
307        self.socket_options = None
308        """Options to pass down to the underlying urllib3 socket
309        """
310
311        self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z"
312        """datetime format
313        """
314
315        self.date_format = "%Y-%m-%d"
316        """date format
317        """

Constructor

server_index
server_operation_index

Default server index

server_variables
server_operation_variables

Default server variables

ignore_operation_servers

Ignore operation servers

temp_folder_path

Temp file folder for downloading files

api_key
api_key_prefix
refresh_api_key_hook

function hook to refresh API key if expired

username

Username for HTTP basic authentication

password

Password for HTTP basic authentication

access_token

Access token

logger

Logging Settings

logger_format: str
433    @property
434    def logger_format(self) -> str:
435        """The logger format.
436
437        The logger_formatter will be updated when sets logger_format.
438
439        :param value: The format string.
440        :type: str
441        """
442        return self.__logger_format

Log format

logger_stream_handler

Log stream handler

logger_file_handler: Optional[logging.FileHandler]

Log file handler

logger_file: Optional[str]
371    @property
372    def logger_file(self) -> Optional[str]:
373        """The logger file.
374
375        If the logger_file is None, then add stream handler and remove file
376        handler. Otherwise, add file handler and remove stream handler.
377
378        :param value: The logger_file path.
379        :type: str
380        """
381        return self.__logger_file

Debug file location

verify_ssl

SSL/TLS verification Set this to false to skip verifying SSL certificate when calling API from https server.

ssl_ca_cert

Set this to customize the certificate file to verify the peer.

ca_cert_data

Set this to verify the peer using PEM (str) or DER (bytes) certificate data.

cert_file

client certificate file

key_file

client key file

assert_hostname

Set this to True/False to enable/disable SSL hostname verification.

tls_server_name

SSL/TLS Server Name Indication (SNI) Set this to the SNI value expected by the server.

connection_pool_maxsize

urllib3 connection pool's maximum number of connections saved per pool. urllib3 uses 1 connection as default value, but this is not the best value when you are making a lot of possibly parallel requests to the same host, which is often the case here. cpu_count * 5 is used as default value to increase performance.

proxy: Optional[str]

Proxy URL

proxy_headers

Proxy headers

safe_chars_for_path_param

Safe chars for path_param

retries

Adding retries to override urllib3 default value 3

client_side_validation
socket_options

Options to pass down to the underlying urllib3 socket

datetime_format

datetime format

date_format

date format

@classmethod
def set_default(cls, default: Optional[Self]) -> None:
336    @classmethod
337    def set_default(cls, default: Optional[Self]) -> None:
338        """Set default instance of configuration.
339
340        It stores default configuration, which can be
341        returned by get_default_copy method.
342
343        :param default: object of Configuration
344        """
345        cls._default = default

Set default instance of configuration.

It stores default configuration, which can be returned by get_default_copy method.

Parameters
  • default: object of Configuration
@classmethod
def get_default_copy(cls) -> Self:
347    @classmethod
348    def get_default_copy(cls) -> Self:
349        """Deprecated. Please use `get_default` instead.
350
351        Deprecated. Please use `get_default` instead.
352
353        :return: The configuration object.
354        """
355        return cls.get_default()

Deprecated. Please use get_default instead.

Deprecated. Please use get_default instead.

Returns

The configuration object.

@classmethod
def get_default(cls) -> Self:
357    @classmethod
358    def get_default(cls) -> Self:
359        """Return the default configuration.
360
361        This method returns newly created, based on default constructor,
362        object of Configuration class or returns a copy of default
363        configuration.
364
365        :return: The configuration object.
366        """
367        if cls._default is None:
368            cls._default = cls()
369        return cls._default

Return the default configuration.

This method returns newly created, based on default constructor, object of Configuration class or returns a copy of default configuration.

Returns

The configuration object.

debug: bool
402    @property
403    def debug(self) -> bool:
404        """Debug status
405
406        :param value: The debug status, True or False.
407        :type: bool
408        """
409        return self.__debug

Debug status

Parameters
  • value: The debug status, True or False.
def get_api_key_with_prefix(self, identifier: str, alias: Optional[str] = None) -> Optional[str]:
456    def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]:
457        """Gets API key (with prefix if set).
458
459        :param identifier: The identifier of apiKey.
460        :param alias: The alternative identifier of apiKey.
461        :return: The token for api key authentication.
462        """
463        if self.refresh_api_key_hook is not None:
464            self.refresh_api_key_hook(self)
465        key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None)
466        if key:
467            prefix = self.api_key_prefix.get(identifier)
468            if prefix:
469                return "%s %s" % (prefix, key)
470            else:
471                return key
472
473        return None

Gets API key (with prefix if set).

Parameters
  • identifier: The identifier of apiKey.
  • alias: The alternative identifier of apiKey.
Returns

The token for api key authentication.

def get_basic_auth_token(self) -> Optional[str]:
475    def get_basic_auth_token(self) -> Optional[str]:
476        """Gets HTTP basic authentication header (string).
477
478        :return: The token for basic HTTP authentication.
479        """
480        username = ""
481        if self.username is not None:
482            username = self.username
483        password = ""
484        if self.password is not None:
485            password = self.password
486        return urllib3.util.make_headers(
487            basic_auth=username + ':' + password
488        ).get('authorization')

Gets HTTP basic authentication header (string).

Returns

The token for basic HTTP authentication.

def auth_settings(self) -> AuthSettings:
490    def auth_settings(self)-> AuthSettings:
491        """Gets Auth Settings dict for api client.
492
493        :return: The Auth Settings information dict.
494        """
495        auth: AuthSettings = {}
496        if self.access_token is not None:
497            auth['bearerAuth'] = {
498                'type': 'bearer',
499                'in': 'header',
500                'format': 'JWT',
501                'key': 'Authorization',
502                'value': 'Bearer ' + self.access_token
503            }
504        return auth

Gets Auth Settings dict for api client.

Returns

The Auth Settings information dict.

def to_debug_report(self) -> str:
506    def to_debug_report(self) -> str:
507        """Gets the essential information for debugging.
508
509        :return: The report for debugging.
510        """
511        return "Python SDK Debug Report:\n"\
512               "OS: {env}\n"\
513               "Python Version: {pyversion}\n"\
514               "Version of the API: 0.1.2\n"\
515               "SDK Package Version: 1.0.0".\
516               format(env=sys.platform, pyversion=sys.version)

Gets the essential information for debugging.

Returns

The report for debugging.

def get_host_settings(self) -> List[HostSetting]:
518    def get_host_settings(self) -> List[HostSetting]:
519        """Gets an array of host settings
520
521        :return: An array of host settings
522        """
523        return [
524            {
525                'url': "https://api.vectorize.io/v1",
526                'description': "Vectorize API",
527            }
528        ]

Gets an array of host settings

Returns

An array of host settings

def get_host_from_settings( self, index: Optional[int], variables: Optional[Dict[str, str]] = None, servers: Optional[List[HostSetting]] = None) -> str:
530    def get_host_from_settings(
531        self,
532        index: Optional[int],
533        variables: Optional[ServerVariablesT]=None,
534        servers: Optional[List[HostSetting]]=None,
535    ) -> str:
536        """Gets host URL based on the index and variables
537        :param index: array index of the host settings
538        :param variables: hash of variable and the corresponding value
539        :param servers: an array of host settings or None
540        :return: URL based on host settings
541        """
542        if index is None:
543            return self._base_path
544
545        variables = {} if variables is None else variables
546        servers = self.get_host_settings() if servers is None else servers
547
548        try:
549            server = servers[index]
550        except IndexError:
551            raise ValueError(
552                "Invalid index {0} when selecting the host settings. "
553                "Must be less than {1}".format(index, len(servers)))
554
555        url = server['url']
556
557        # go through variables and replace placeholders
558        for variable_name, variable in server.get('variables', {}).items():
559            used_value = variables.get(
560                variable_name, variable['default_value'])
561
562            if 'enum_values' in variable \
563                    and used_value not in variable['enum_values']:
564                raise ValueError(
565                    "The variable `{0}` in the host URL has invalid value "
566                    "{1}. Must be {2}.".format(
567                        variable_name, variables[variable_name],
568                        variable['enum_values']))
569
570            url = url.replace("{" + variable_name + "}", used_value)
571
572        return url

Gets host URL based on the index and variables

Parameters
  • index: array index of the host settings
  • variables: hash of variable and the corresponding value
  • servers: an array of host settings or None
Returns

URL based on host settings

host: str
574    @property
575    def host(self) -> str:
576        """Return generated host."""
577        return self.get_host_from_settings(self.server_index, variables=self.server_variables)

Return generated host.