vectorize_client.configuration
Vectorize API (Beta)
API for Vectorize services
The version of the OpenAPI document: 0.0.1 Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
1# coding: utf-8 2 3""" 4 Vectorize API (Beta) 5 6 API for Vectorize services 7 8 The version of the OpenAPI document: 0.0.1 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 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 165 :Example: 166 """ 167 168 _default: ClassVar[Optional[Self]] = None 169 170 def __init__( 171 self, 172 host: Optional[str]=None, 173 api_key: Optional[Dict[str, str]]=None, 174 api_key_prefix: Optional[Dict[str, str]]=None, 175 username: Optional[str]=None, 176 password: Optional[str]=None, 177 access_token: Optional[str]=None, 178 server_index: Optional[int]=None, 179 server_variables: Optional[ServerVariablesT]=None, 180 server_operation_index: Optional[Dict[int, int]]=None, 181 server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None, 182 ignore_operation_servers: bool=False, 183 ssl_ca_cert: Optional[str]=None, 184 retries: Optional[int] = None, 185 *, 186 debug: Optional[bool] = None, 187 ) -> None: 188 """Constructor 189 """ 190 self._base_path = "https://api.vectorize.io/v1" if host is None else host 191 """Default Base url 192 """ 193 self.server_index = 0 if server_index is None and host is None else server_index 194 self.server_operation_index = server_operation_index or {} 195 """Default server index 196 """ 197 self.server_variables = server_variables or {} 198 self.server_operation_variables = server_operation_variables or {} 199 """Default server variables 200 """ 201 self.ignore_operation_servers = ignore_operation_servers 202 """Ignore operation servers 203 """ 204 self.temp_folder_path = None 205 """Temp file folder for downloading files 206 """ 207 # Authentication Settings 208 self.api_key = {} 209 if api_key: 210 self.api_key = api_key 211 """dict to store API key(s) 212 """ 213 self.api_key_prefix = {} 214 if api_key_prefix: 215 self.api_key_prefix = api_key_prefix 216 """dict to store API prefix (e.g. Bearer) 217 """ 218 self.refresh_api_key_hook = None 219 """function hook to refresh API key if expired 220 """ 221 self.username = username 222 """Username for HTTP basic authentication 223 """ 224 self.password = password 225 """Password for HTTP basic authentication 226 """ 227 self.access_token = access_token 228 """Access token 229 """ 230 self.logger = {} 231 """Logging Settings 232 """ 233 self.logger["package_logger"] = logging.getLogger("vectorize_client") 234 self.logger["urllib3_logger"] = logging.getLogger("urllib3") 235 self.logger_format = '%(asctime)s %(levelname)s %(message)s' 236 """Log format 237 """ 238 self.logger_stream_handler = None 239 """Log stream handler 240 """ 241 self.logger_file_handler: Optional[FileHandler] = None 242 """Log file handler 243 """ 244 self.logger_file = None 245 """Debug file location 246 """ 247 if debug is not None: 248 self.debug = debug 249 else: 250 self.__debug = False 251 """Debug switch 252 """ 253 254 self.verify_ssl = True 255 """SSL/TLS verification 256 Set this to false to skip verifying SSL certificate when calling API 257 from https server. 258 """ 259 self.ssl_ca_cert = ssl_ca_cert 260 """Set this to customize the certificate file to verify the peer. 261 """ 262 self.cert_file = None 263 """client certificate file 264 """ 265 self.key_file = None 266 """client key file 267 """ 268 self.assert_hostname = None 269 """Set this to True/False to enable/disable SSL hostname verification. 270 """ 271 self.tls_server_name = None 272 """SSL/TLS Server Name Indication (SNI) 273 Set this to the SNI value expected by the server. 274 """ 275 276 self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 277 """urllib3 connection pool's maximum number of connections saved 278 per pool. urllib3 uses 1 connection as default value, but this is 279 not the best value when you are making a lot of possibly parallel 280 requests to the same host, which is often the case here. 281 cpu_count * 5 is used as default value to increase performance. 282 """ 283 284 self.proxy: Optional[str] = None 285 """Proxy URL 286 """ 287 self.proxy_headers = None 288 """Proxy headers 289 """ 290 self.safe_chars_for_path_param = '' 291 """Safe chars for path_param 292 """ 293 self.retries = retries 294 """Adding retries to override urllib3 default value 3 295 """ 296 # Enable client side validation 297 self.client_side_validation = True 298 299 self.socket_options = None 300 """Options to pass down to the underlying urllib3 socket 301 """ 302 303 self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" 304 """datetime format 305 """ 306 307 self.date_format = "%Y-%m-%d" 308 """date format 309 """ 310 311 def __deepcopy__(self, memo: Dict[int, Any]) -> Self: 312 cls = self.__class__ 313 result = cls.__new__(cls) 314 memo[id(self)] = result 315 for k, v in self.__dict__.items(): 316 if k not in ('logger', 'logger_file_handler'): 317 setattr(result, k, copy.deepcopy(v, memo)) 318 # shallow copy of loggers 319 result.logger = copy.copy(self.logger) 320 # use setters to configure loggers 321 result.logger_file = self.logger_file 322 result.debug = self.debug 323 return result 324 325 def __setattr__(self, name: str, value: Any) -> None: 326 object.__setattr__(self, name, value) 327 328 @classmethod 329 def set_default(cls, default: Optional[Self]) -> None: 330 """Set default instance of configuration. 331 332 It stores default configuration, which can be 333 returned by get_default_copy method. 334 335 :param default: object of Configuration 336 """ 337 cls._default = default 338 339 @classmethod 340 def get_default_copy(cls) -> Self: 341 """Deprecated. Please use `get_default` instead. 342 343 Deprecated. Please use `get_default` instead. 344 345 :return: The configuration object. 346 """ 347 return cls.get_default() 348 349 @classmethod 350 def get_default(cls) -> Self: 351 """Return the default configuration. 352 353 This method returns newly created, based on default constructor, 354 object of Configuration class or returns a copy of default 355 configuration. 356 357 :return: The configuration object. 358 """ 359 if cls._default is None: 360 cls._default = cls() 361 return cls._default 362 363 @property 364 def logger_file(self) -> Optional[str]: 365 """The logger file. 366 367 If the logger_file is None, then add stream handler and remove file 368 handler. Otherwise, add file handler and remove stream handler. 369 370 :param value: The logger_file path. 371 :type: str 372 """ 373 return self.__logger_file 374 375 @logger_file.setter 376 def logger_file(self, value: Optional[str]) -> None: 377 """The logger file. 378 379 If the logger_file is None, then add stream handler and remove file 380 handler. Otherwise, add file handler and remove stream handler. 381 382 :param value: The logger_file path. 383 :type: str 384 """ 385 self.__logger_file = value 386 if self.__logger_file: 387 # If set logging file, 388 # then add file handler and remove stream handler. 389 self.logger_file_handler = logging.FileHandler(self.__logger_file) 390 self.logger_file_handler.setFormatter(self.logger_formatter) 391 for _, logger in self.logger.items(): 392 logger.addHandler(self.logger_file_handler) 393 394 @property 395 def debug(self) -> bool: 396 """Debug status 397 398 :param value: The debug status, True or False. 399 :type: bool 400 """ 401 return self.__debug 402 403 @debug.setter 404 def debug(self, value: bool) -> None: 405 """Debug status 406 407 :param value: The debug status, True or False. 408 :type: bool 409 """ 410 self.__debug = value 411 if self.__debug: 412 # if debug status is True, turn on debug logging 413 for _, logger in self.logger.items(): 414 logger.setLevel(logging.DEBUG) 415 # turn on httplib debug 416 httplib.HTTPConnection.debuglevel = 1 417 else: 418 # if debug status is False, turn off debug logging, 419 # setting log level to default `logging.WARNING` 420 for _, logger in self.logger.items(): 421 logger.setLevel(logging.WARNING) 422 # turn off httplib debug 423 httplib.HTTPConnection.debuglevel = 0 424 425 @property 426 def logger_format(self) -> str: 427 """The logger format. 428 429 The logger_formatter will be updated when sets logger_format. 430 431 :param value: The format string. 432 :type: str 433 """ 434 return self.__logger_format 435 436 @logger_format.setter 437 def logger_format(self, value: str) -> None: 438 """The logger format. 439 440 The logger_formatter will be updated when sets logger_format. 441 442 :param value: The format string. 443 :type: str 444 """ 445 self.__logger_format = value 446 self.logger_formatter = logging.Formatter(self.__logger_format) 447 448 def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]: 449 """Gets API key (with prefix if set). 450 451 :param identifier: The identifier of apiKey. 452 :param alias: The alternative identifier of apiKey. 453 :return: The token for api key authentication. 454 """ 455 if self.refresh_api_key_hook is not None: 456 self.refresh_api_key_hook(self) 457 key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) 458 if key: 459 prefix = self.api_key_prefix.get(identifier) 460 if prefix: 461 return "%s %s" % (prefix, key) 462 else: 463 return key 464 465 return None 466 467 def get_basic_auth_token(self) -> Optional[str]: 468 """Gets HTTP basic authentication header (string). 469 470 :return: The token for basic HTTP authentication. 471 """ 472 username = "" 473 if self.username is not None: 474 username = self.username 475 password = "" 476 if self.password is not None: 477 password = self.password 478 return urllib3.util.make_headers( 479 basic_auth=username + ':' + password 480 ).get('authorization') 481 482 def auth_settings(self)-> AuthSettings: 483 """Gets Auth Settings dict for api client. 484 485 :return: The Auth Settings information dict. 486 """ 487 auth: AuthSettings = {} 488 if self.access_token is not None: 489 auth['bearerAuth'] = { 490 'type': 'bearer', 491 'in': 'header', 492 'format': 'JWT', 493 'key': 'Authorization', 494 'value': 'Bearer ' + self.access_token 495 } 496 return auth 497 498 def to_debug_report(self) -> str: 499 """Gets the essential information for debugging. 500 501 :return: The report for debugging. 502 """ 503 return "Python SDK Debug Report:\n"\ 504 "OS: {env}\n"\ 505 "Python Version: {pyversion}\n"\ 506 "Version of the API: 0.0.1\n"\ 507 "SDK Package Version: 1.0.0".\ 508 format(env=sys.platform, pyversion=sys.version) 509 510 def get_host_settings(self) -> List[HostSetting]: 511 """Gets an array of host settings 512 513 :return: An array of host settings 514 """ 515 return [ 516 { 517 'url': "https://api.vectorize.io/v1", 518 'description': "Vectorize API", 519 } 520 ] 521 522 def get_host_from_settings( 523 self, 524 index: Optional[int], 525 variables: Optional[ServerVariablesT]=None, 526 servers: Optional[List[HostSetting]]=None, 527 ) -> str: 528 """Gets host URL based on the index and variables 529 :param index: array index of the host settings 530 :param variables: hash of variable and the corresponding value 531 :param servers: an array of host settings or None 532 :return: URL based on host settings 533 """ 534 if index is None: 535 return self._base_path 536 537 variables = {} if variables is None else variables 538 servers = self.get_host_settings() if servers is None else servers 539 540 try: 541 server = servers[index] 542 except IndexError: 543 raise ValueError( 544 "Invalid index {0} when selecting the host settings. " 545 "Must be less than {1}".format(index, len(servers))) 546 547 url = server['url'] 548 549 # go through variables and replace placeholders 550 for variable_name, variable in server.get('variables', {}).items(): 551 used_value = variables.get( 552 variable_name, variable['default_value']) 553 554 if 'enum_values' in variable \ 555 and used_value not in variable['enum_values']: 556 raise ValueError( 557 "The variable `{0}` in the host URL has invalid value " 558 "{1}. Must be {2}.".format( 559 variable_name, variables[variable_name], 560 variable['enum_values'])) 561 562 url = url.replace("{" + variable_name + "}", used_value) 563 564 return url 565 566 @property 567 def host(self) -> str: 568 """Return generated host.""" 569 return self.get_host_from_settings(self.server_index, variables=self.server_variables) 570 571 @host.setter 572 def host(self, value: str) -> None: 573 """Fix base path.""" 574 self._base_path = value 575 self.server_index = None
129class HostSetting(TypedDict): 130 url: str 131 description: str 132 variables: NotRequired[Dict[str, HostSettingVariable]]
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 166 :Example: 167 """ 168 169 _default: ClassVar[Optional[Self]] = None 170 171 def __init__( 172 self, 173 host: Optional[str]=None, 174 api_key: Optional[Dict[str, str]]=None, 175 api_key_prefix: Optional[Dict[str, str]]=None, 176 username: Optional[str]=None, 177 password: Optional[str]=None, 178 access_token: Optional[str]=None, 179 server_index: Optional[int]=None, 180 server_variables: Optional[ServerVariablesT]=None, 181 server_operation_index: Optional[Dict[int, int]]=None, 182 server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None, 183 ignore_operation_servers: bool=False, 184 ssl_ca_cert: Optional[str]=None, 185 retries: Optional[int] = None, 186 *, 187 debug: Optional[bool] = None, 188 ) -> None: 189 """Constructor 190 """ 191 self._base_path = "https://api.vectorize.io/v1" if host is None else host 192 """Default Base url 193 """ 194 self.server_index = 0 if server_index is None and host is None else server_index 195 self.server_operation_index = server_operation_index or {} 196 """Default server index 197 """ 198 self.server_variables = server_variables or {} 199 self.server_operation_variables = server_operation_variables or {} 200 """Default server variables 201 """ 202 self.ignore_operation_servers = ignore_operation_servers 203 """Ignore operation servers 204 """ 205 self.temp_folder_path = None 206 """Temp file folder for downloading files 207 """ 208 # Authentication Settings 209 self.api_key = {} 210 if api_key: 211 self.api_key = api_key 212 """dict to store API key(s) 213 """ 214 self.api_key_prefix = {} 215 if api_key_prefix: 216 self.api_key_prefix = api_key_prefix 217 """dict to store API prefix (e.g. Bearer) 218 """ 219 self.refresh_api_key_hook = None 220 """function hook to refresh API key if expired 221 """ 222 self.username = username 223 """Username for HTTP basic authentication 224 """ 225 self.password = password 226 """Password for HTTP basic authentication 227 """ 228 self.access_token = access_token 229 """Access token 230 """ 231 self.logger = {} 232 """Logging Settings 233 """ 234 self.logger["package_logger"] = logging.getLogger("vectorize_client") 235 self.logger["urllib3_logger"] = logging.getLogger("urllib3") 236 self.logger_format = '%(asctime)s %(levelname)s %(message)s' 237 """Log format 238 """ 239 self.logger_stream_handler = None 240 """Log stream handler 241 """ 242 self.logger_file_handler: Optional[FileHandler] = None 243 """Log file handler 244 """ 245 self.logger_file = None 246 """Debug file location 247 """ 248 if debug is not None: 249 self.debug = debug 250 else: 251 self.__debug = False 252 """Debug switch 253 """ 254 255 self.verify_ssl = True 256 """SSL/TLS verification 257 Set this to false to skip verifying SSL certificate when calling API 258 from https server. 259 """ 260 self.ssl_ca_cert = ssl_ca_cert 261 """Set this to customize the certificate file to verify the peer. 262 """ 263 self.cert_file = None 264 """client certificate file 265 """ 266 self.key_file = None 267 """client key file 268 """ 269 self.assert_hostname = None 270 """Set this to True/False to enable/disable SSL hostname verification. 271 """ 272 self.tls_server_name = None 273 """SSL/TLS Server Name Indication (SNI) 274 Set this to the SNI value expected by the server. 275 """ 276 277 self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 278 """urllib3 connection pool's maximum number of connections saved 279 per pool. urllib3 uses 1 connection as default value, but this is 280 not the best value when you are making a lot of possibly parallel 281 requests to the same host, which is often the case here. 282 cpu_count * 5 is used as default value to increase performance. 283 """ 284 285 self.proxy: Optional[str] = None 286 """Proxy URL 287 """ 288 self.proxy_headers = None 289 """Proxy headers 290 """ 291 self.safe_chars_for_path_param = '' 292 """Safe chars for path_param 293 """ 294 self.retries = retries 295 """Adding retries to override urllib3 default value 3 296 """ 297 # Enable client side validation 298 self.client_side_validation = True 299 300 self.socket_options = None 301 """Options to pass down to the underlying urllib3 socket 302 """ 303 304 self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" 305 """datetime format 306 """ 307 308 self.date_format = "%Y-%m-%d" 309 """date format 310 """ 311 312 def __deepcopy__(self, memo: Dict[int, Any]) -> Self: 313 cls = self.__class__ 314 result = cls.__new__(cls) 315 memo[id(self)] = result 316 for k, v in self.__dict__.items(): 317 if k not in ('logger', 'logger_file_handler'): 318 setattr(result, k, copy.deepcopy(v, memo)) 319 # shallow copy of loggers 320 result.logger = copy.copy(self.logger) 321 # use setters to configure loggers 322 result.logger_file = self.logger_file 323 result.debug = self.debug 324 return result 325 326 def __setattr__(self, name: str, value: Any) -> None: 327 object.__setattr__(self, name, value) 328 329 @classmethod 330 def set_default(cls, default: Optional[Self]) -> None: 331 """Set default instance of configuration. 332 333 It stores default configuration, which can be 334 returned by get_default_copy method. 335 336 :param default: object of Configuration 337 """ 338 cls._default = default 339 340 @classmethod 341 def get_default_copy(cls) -> Self: 342 """Deprecated. Please use `get_default` instead. 343 344 Deprecated. Please use `get_default` instead. 345 346 :return: The configuration object. 347 """ 348 return cls.get_default() 349 350 @classmethod 351 def get_default(cls) -> Self: 352 """Return the default configuration. 353 354 This method returns newly created, based on default constructor, 355 object of Configuration class or returns a copy of default 356 configuration. 357 358 :return: The configuration object. 359 """ 360 if cls._default is None: 361 cls._default = cls() 362 return cls._default 363 364 @property 365 def logger_file(self) -> Optional[str]: 366 """The logger file. 367 368 If the logger_file is None, then add stream handler and remove file 369 handler. Otherwise, add file handler and remove stream handler. 370 371 :param value: The logger_file path. 372 :type: str 373 """ 374 return self.__logger_file 375 376 @logger_file.setter 377 def logger_file(self, value: Optional[str]) -> None: 378 """The logger file. 379 380 If the logger_file is None, then add stream handler and remove file 381 handler. Otherwise, add file handler and remove stream handler. 382 383 :param value: The logger_file path. 384 :type: str 385 """ 386 self.__logger_file = value 387 if self.__logger_file: 388 # If set logging file, 389 # then add file handler and remove stream handler. 390 self.logger_file_handler = logging.FileHandler(self.__logger_file) 391 self.logger_file_handler.setFormatter(self.logger_formatter) 392 for _, logger in self.logger.items(): 393 logger.addHandler(self.logger_file_handler) 394 395 @property 396 def debug(self) -> bool: 397 """Debug status 398 399 :param value: The debug status, True or False. 400 :type: bool 401 """ 402 return self.__debug 403 404 @debug.setter 405 def debug(self, value: bool) -> None: 406 """Debug status 407 408 :param value: The debug status, True or False. 409 :type: bool 410 """ 411 self.__debug = value 412 if self.__debug: 413 # if debug status is True, turn on debug logging 414 for _, logger in self.logger.items(): 415 logger.setLevel(logging.DEBUG) 416 # turn on httplib debug 417 httplib.HTTPConnection.debuglevel = 1 418 else: 419 # if debug status is False, turn off debug logging, 420 # setting log level to default `logging.WARNING` 421 for _, logger in self.logger.items(): 422 logger.setLevel(logging.WARNING) 423 # turn off httplib debug 424 httplib.HTTPConnection.debuglevel = 0 425 426 @property 427 def logger_format(self) -> str: 428 """The logger format. 429 430 The logger_formatter will be updated when sets logger_format. 431 432 :param value: The format string. 433 :type: str 434 """ 435 return self.__logger_format 436 437 @logger_format.setter 438 def logger_format(self, value: str) -> None: 439 """The logger format. 440 441 The logger_formatter will be updated when sets logger_format. 442 443 :param value: The format string. 444 :type: str 445 """ 446 self.__logger_format = value 447 self.logger_formatter = logging.Formatter(self.__logger_format) 448 449 def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]: 450 """Gets API key (with prefix if set). 451 452 :param identifier: The identifier of apiKey. 453 :param alias: The alternative identifier of apiKey. 454 :return: The token for api key authentication. 455 """ 456 if self.refresh_api_key_hook is not None: 457 self.refresh_api_key_hook(self) 458 key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) 459 if key: 460 prefix = self.api_key_prefix.get(identifier) 461 if prefix: 462 return "%s %s" % (prefix, key) 463 else: 464 return key 465 466 return None 467 468 def get_basic_auth_token(self) -> Optional[str]: 469 """Gets HTTP basic authentication header (string). 470 471 :return: The token for basic HTTP authentication. 472 """ 473 username = "" 474 if self.username is not None: 475 username = self.username 476 password = "" 477 if self.password is not None: 478 password = self.password 479 return urllib3.util.make_headers( 480 basic_auth=username + ':' + password 481 ).get('authorization') 482 483 def auth_settings(self)-> AuthSettings: 484 """Gets Auth Settings dict for api client. 485 486 :return: The Auth Settings information dict. 487 """ 488 auth: AuthSettings = {} 489 if self.access_token is not None: 490 auth['bearerAuth'] = { 491 'type': 'bearer', 492 'in': 'header', 493 'format': 'JWT', 494 'key': 'Authorization', 495 'value': 'Bearer ' + self.access_token 496 } 497 return auth 498 499 def to_debug_report(self) -> str: 500 """Gets the essential information for debugging. 501 502 :return: The report for debugging. 503 """ 504 return "Python SDK Debug Report:\n"\ 505 "OS: {env}\n"\ 506 "Python Version: {pyversion}\n"\ 507 "Version of the API: 0.0.1\n"\ 508 "SDK Package Version: 1.0.0".\ 509 format(env=sys.platform, pyversion=sys.version) 510 511 def get_host_settings(self) -> List[HostSetting]: 512 """Gets an array of host settings 513 514 :return: An array of host settings 515 """ 516 return [ 517 { 518 'url': "https://api.vectorize.io/v1", 519 'description': "Vectorize API", 520 } 521 ] 522 523 def get_host_from_settings( 524 self, 525 index: Optional[int], 526 variables: Optional[ServerVariablesT]=None, 527 servers: Optional[List[HostSetting]]=None, 528 ) -> str: 529 """Gets host URL based on the index and variables 530 :param index: array index of the host settings 531 :param variables: hash of variable and the corresponding value 532 :param servers: an array of host settings or None 533 :return: URL based on host settings 534 """ 535 if index is None: 536 return self._base_path 537 538 variables = {} if variables is None else variables 539 servers = self.get_host_settings() if servers is None else servers 540 541 try: 542 server = servers[index] 543 except IndexError: 544 raise ValueError( 545 "Invalid index {0} when selecting the host settings. " 546 "Must be less than {1}".format(index, len(servers))) 547 548 url = server['url'] 549 550 # go through variables and replace placeholders 551 for variable_name, variable in server.get('variables', {}).items(): 552 used_value = variables.get( 553 variable_name, variable['default_value']) 554 555 if 'enum_values' in variable \ 556 and used_value not in variable['enum_values']: 557 raise ValueError( 558 "The variable `{0}` in the host URL has invalid value " 559 "{1}. Must be {2}.".format( 560 variable_name, variables[variable_name], 561 variable['enum_values'])) 562 563 url = url.replace("{" + variable_name + "}", used_value) 564 565 return url 566 567 @property 568 def host(self) -> str: 569 """Return generated host.""" 570 return self.get_host_from_settings(self.server_index, variables=self.server_variables) 571 572 @host.setter 573 def host(self, value: str) -> None: 574 """Fix base path.""" 575 self._base_path = value 576 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.
:Example:
171 def __init__( 172 self, 173 host: Optional[str]=None, 174 api_key: Optional[Dict[str, str]]=None, 175 api_key_prefix: Optional[Dict[str, str]]=None, 176 username: Optional[str]=None, 177 password: Optional[str]=None, 178 access_token: Optional[str]=None, 179 server_index: Optional[int]=None, 180 server_variables: Optional[ServerVariablesT]=None, 181 server_operation_index: Optional[Dict[int, int]]=None, 182 server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None, 183 ignore_operation_servers: bool=False, 184 ssl_ca_cert: Optional[str]=None, 185 retries: Optional[int] = None, 186 *, 187 debug: Optional[bool] = None, 188 ) -> None: 189 """Constructor 190 """ 191 self._base_path = "https://api.vectorize.io/v1" if host is None else host 192 """Default Base url 193 """ 194 self.server_index = 0 if server_index is None and host is None else server_index 195 self.server_operation_index = server_operation_index or {} 196 """Default server index 197 """ 198 self.server_variables = server_variables or {} 199 self.server_operation_variables = server_operation_variables or {} 200 """Default server variables 201 """ 202 self.ignore_operation_servers = ignore_operation_servers 203 """Ignore operation servers 204 """ 205 self.temp_folder_path = None 206 """Temp file folder for downloading files 207 """ 208 # Authentication Settings 209 self.api_key = {} 210 if api_key: 211 self.api_key = api_key 212 """dict to store API key(s) 213 """ 214 self.api_key_prefix = {} 215 if api_key_prefix: 216 self.api_key_prefix = api_key_prefix 217 """dict to store API prefix (e.g. Bearer) 218 """ 219 self.refresh_api_key_hook = None 220 """function hook to refresh API key if expired 221 """ 222 self.username = username 223 """Username for HTTP basic authentication 224 """ 225 self.password = password 226 """Password for HTTP basic authentication 227 """ 228 self.access_token = access_token 229 """Access token 230 """ 231 self.logger = {} 232 """Logging Settings 233 """ 234 self.logger["package_logger"] = logging.getLogger("vectorize_client") 235 self.logger["urllib3_logger"] = logging.getLogger("urllib3") 236 self.logger_format = '%(asctime)s %(levelname)s %(message)s' 237 """Log format 238 """ 239 self.logger_stream_handler = None 240 """Log stream handler 241 """ 242 self.logger_file_handler: Optional[FileHandler] = None 243 """Log file handler 244 """ 245 self.logger_file = None 246 """Debug file location 247 """ 248 if debug is not None: 249 self.debug = debug 250 else: 251 self.__debug = False 252 """Debug switch 253 """ 254 255 self.verify_ssl = True 256 """SSL/TLS verification 257 Set this to false to skip verifying SSL certificate when calling API 258 from https server. 259 """ 260 self.ssl_ca_cert = ssl_ca_cert 261 """Set this to customize the certificate file to verify the peer. 262 """ 263 self.cert_file = None 264 """client certificate file 265 """ 266 self.key_file = None 267 """client key file 268 """ 269 self.assert_hostname = None 270 """Set this to True/False to enable/disable SSL hostname verification. 271 """ 272 self.tls_server_name = None 273 """SSL/TLS Server Name Indication (SNI) 274 Set this to the SNI value expected by the server. 275 """ 276 277 self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 278 """urllib3 connection pool's maximum number of connections saved 279 per pool. urllib3 uses 1 connection as default value, but this is 280 not the best value when you are making a lot of possibly parallel 281 requests to the same host, which is often the case here. 282 cpu_count * 5 is used as default value to increase performance. 283 """ 284 285 self.proxy: Optional[str] = None 286 """Proxy URL 287 """ 288 self.proxy_headers = None 289 """Proxy headers 290 """ 291 self.safe_chars_for_path_param = '' 292 """Safe chars for path_param 293 """ 294 self.retries = retries 295 """Adding retries to override urllib3 default value 3 296 """ 297 # Enable client side validation 298 self.client_side_validation = True 299 300 self.socket_options = None 301 """Options to pass down to the underlying urllib3 socket 302 """ 303 304 self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" 305 """datetime format 306 """ 307 308 self.date_format = "%Y-%m-%d" 309 """date format 310 """
Constructor
426 @property 427 def logger_format(self) -> str: 428 """The logger format. 429 430 The logger_formatter will be updated when sets logger_format. 431 432 :param value: The format string. 433 :type: str 434 """ 435 return self.__logger_format
Log format
364 @property 365 def logger_file(self) -> Optional[str]: 366 """The logger file. 367 368 If the logger_file is None, then add stream handler and remove file 369 handler. Otherwise, add file handler and remove stream handler. 370 371 :param value: The logger_file path. 372 :type: str 373 """ 374 return self.__logger_file
Debug file location
SSL/TLS verification Set this to false to skip verifying SSL certificate when calling API from https server.
SSL/TLS Server Name Indication (SNI) Set this to the SNI value expected by the server.
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.
329 @classmethod 330 def set_default(cls, default: Optional[Self]) -> None: 331 """Set default instance of configuration. 332 333 It stores default configuration, which can be 334 returned by get_default_copy method. 335 336 :param default: object of Configuration 337 """ 338 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
340 @classmethod 341 def get_default_copy(cls) -> Self: 342 """Deprecated. Please use `get_default` instead. 343 344 Deprecated. Please use `get_default` instead. 345 346 :return: The configuration object. 347 """ 348 return cls.get_default()
Deprecated. Please use get_default
instead.
Deprecated. Please use get_default
instead.
Returns
The configuration object.
350 @classmethod 351 def get_default(cls) -> Self: 352 """Return the default configuration. 353 354 This method returns newly created, based on default constructor, 355 object of Configuration class or returns a copy of default 356 configuration. 357 358 :return: The configuration object. 359 """ 360 if cls._default is None: 361 cls._default = cls() 362 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.
395 @property 396 def debug(self) -> bool: 397 """Debug status 398 399 :param value: The debug status, True or False. 400 :type: bool 401 """ 402 return self.__debug
Debug status
Parameters
- value: The debug status, True or False.
449 def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]: 450 """Gets API key (with prefix if set). 451 452 :param identifier: The identifier of apiKey. 453 :param alias: The alternative identifier of apiKey. 454 :return: The token for api key authentication. 455 """ 456 if self.refresh_api_key_hook is not None: 457 self.refresh_api_key_hook(self) 458 key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) 459 if key: 460 prefix = self.api_key_prefix.get(identifier) 461 if prefix: 462 return "%s %s" % (prefix, key) 463 else: 464 return key 465 466 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.
468 def get_basic_auth_token(self) -> Optional[str]: 469 """Gets HTTP basic authentication header (string). 470 471 :return: The token for basic HTTP authentication. 472 """ 473 username = "" 474 if self.username is not None: 475 username = self.username 476 password = "" 477 if self.password is not None: 478 password = self.password 479 return urllib3.util.make_headers( 480 basic_auth=username + ':' + password 481 ).get('authorization')
Gets HTTP basic authentication header (string).
Returns
The token for basic HTTP authentication.
483 def auth_settings(self)-> AuthSettings: 484 """Gets Auth Settings dict for api client. 485 486 :return: The Auth Settings information dict. 487 """ 488 auth: AuthSettings = {} 489 if self.access_token is not None: 490 auth['bearerAuth'] = { 491 'type': 'bearer', 492 'in': 'header', 493 'format': 'JWT', 494 'key': 'Authorization', 495 'value': 'Bearer ' + self.access_token 496 } 497 return auth
Gets Auth Settings dict for api client.
Returns
The Auth Settings information dict.
499 def to_debug_report(self) -> str: 500 """Gets the essential information for debugging. 501 502 :return: The report for debugging. 503 """ 504 return "Python SDK Debug Report:\n"\ 505 "OS: {env}\n"\ 506 "Python Version: {pyversion}\n"\ 507 "Version of the API: 0.0.1\n"\ 508 "SDK Package Version: 1.0.0".\ 509 format(env=sys.platform, pyversion=sys.version)
Gets the essential information for debugging.
Returns
The report for debugging.
511 def get_host_settings(self) -> List[HostSetting]: 512 """Gets an array of host settings 513 514 :return: An array of host settings 515 """ 516 return [ 517 { 518 'url': "https://api.vectorize.io/v1", 519 'description': "Vectorize API", 520 } 521 ]
Gets an array of host settings
Returns
An array of host settings
523 def get_host_from_settings( 524 self, 525 index: Optional[int], 526 variables: Optional[ServerVariablesT]=None, 527 servers: Optional[List[HostSetting]]=None, 528 ) -> str: 529 """Gets host URL based on the index and variables 530 :param index: array index of the host settings 531 :param variables: hash of variable and the corresponding value 532 :param servers: an array of host settings or None 533 :return: URL based on host settings 534 """ 535 if index is None: 536 return self._base_path 537 538 variables = {} if variables is None else variables 539 servers = self.get_host_settings() if servers is None else servers 540 541 try: 542 server = servers[index] 543 except IndexError: 544 raise ValueError( 545 "Invalid index {0} when selecting the host settings. " 546 "Must be less than {1}".format(index, len(servers))) 547 548 url = server['url'] 549 550 # go through variables and replace placeholders 551 for variable_name, variable in server.get('variables', {}).items(): 552 used_value = variables.get( 553 variable_name, variable['default_value']) 554 555 if 'enum_values' in variable \ 556 and used_value not in variable['enum_values']: 557 raise ValueError( 558 "The variable `{0}` in the host URL has invalid value " 559 "{1}. Must be {2}.".format( 560 variable_name, variables[variable_name], 561 variable['enum_values'])) 562 563 url = url.replace("{" + variable_name + "}", used_value) 564 565 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