pinecone.core.client.api_client

Pinecone API

No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501

The version of the OpenAPI document: version not set Contact: support@pinecone.io Generated by: https://openapi-generator.tech

  1"""
  2    Pinecone API
  3
  4    No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)  # noqa: E501
  5
  6    The version of the OpenAPI document: version not set
  7    Contact: support@pinecone.io
  8    Generated by: https://openapi-generator.tech
  9"""
 10
 11
 12import json
 13import atexit
 14import mimetypes
 15from multiprocessing.pool import ThreadPool
 16import io
 17import os
 18import re
 19import typing
 20from urllib.parse import quote
 21from urllib3.fields import RequestField
 22
 23
 24from pinecone.core.client import rest
 25from pinecone.core.client.configuration import Configuration
 26from pinecone.core.client.exceptions import ApiTypeError, ApiValueError, ApiException
 27from pinecone.core.client.model_utils import (
 28    ModelNormal,
 29    ModelSimple,
 30    ModelComposed,
 31    check_allowed_values,
 32    check_validations,
 33    date,
 34    datetime,
 35    deserialize_file,
 36    file_type,
 37    model_to_dict,
 38    none_type,
 39    validate_and_convert_types,
 40)
 41
 42
 43class ApiClient(object):
 44    """Generic API client for OpenAPI client library builds.
 45
 46    OpenAPI generic API client. This client handles the client-
 47    server communication, and is invariant across implementations. Specifics of
 48    the methods and models for each application are generated from the OpenAPI
 49    templates.
 50
 51    NOTE: This class is auto generated by OpenAPI Generator.
 52    Ref: https://openapi-generator.tech
 53    Do not edit the class manually.
 54
 55    :param configuration: .Configuration object for this client
 56    :param header_name: a header to pass when making calls to the API.
 57    :param header_value: a header value to pass when making calls to
 58        the API.
 59    :param cookie: a cookie to include in the header when making calls
 60        to the API
 61    :param pool_threads: The number of threads to use for async requests
 62        to the API. More threads means more concurrent API requests.
 63    """
 64
 65    _pool = None
 66
 67    def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None, pool_threads=1):
 68        if configuration is None:
 69            configuration = Configuration.get_default_copy()
 70        self.configuration = configuration
 71        self.pool_threads = pool_threads
 72
 73        self.rest_client = rest.RESTClientObject(configuration)
 74        self.default_headers = {}
 75        if header_name is not None:
 76            self.default_headers[header_name] = header_value
 77        self.cookie = cookie
 78        # Set default User-Agent.
 79        self.user_agent = "OpenAPI-Generator/1.0.0/python"
 80
 81    def __enter__(self):
 82        return self
 83
 84    def __exit__(self, exc_type, exc_value, traceback):
 85        self.close()
 86
 87    def close(self):
 88        if self._pool:
 89            self._pool.close()
 90            self._pool.join()
 91            self._pool = None
 92            if hasattr(atexit, "unregister"):
 93                atexit.unregister(self.close)
 94
 95    @property
 96    def pool(self):
 97        """Create thread pool on first request
 98        avoids instantiating unused threadpool for blocking clients.
 99        """
100        if self._pool is None:
101            atexit.register(self.close)
102            self._pool = ThreadPool(self.pool_threads)
103        return self._pool
104
105    @property
106    def user_agent(self):
107        """User agent for this API client"""
108        return self.default_headers["User-Agent"]
109
110    @user_agent.setter
111    def user_agent(self, value):
112        self.default_headers["User-Agent"] = value
113
114    def set_default_header(self, header_name, header_value):
115        self.default_headers[header_name] = header_value
116
117    def __call_api(
118        self,
119        resource_path: str,
120        method: str,
121        path_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
122        query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
123        header_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
124        body: typing.Optional[typing.Any] = None,
125        post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
126        files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None,
127        response_type: typing.Optional[typing.Tuple[typing.Any]] = None,
128        auth_settings: typing.Optional[typing.List[str]] = None,
129        _return_http_data_only: typing.Optional[bool] = None,
130        collection_formats: typing.Optional[typing.Dict[str, str]] = None,
131        _preload_content: bool = True,
132        _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None,
133        _host: typing.Optional[str] = None,
134        _check_type: typing.Optional[bool] = None,
135    ):
136        config = self.configuration
137
138        # header parameters
139        header_params = header_params or {}
140        header_params.update(self.default_headers)
141        if self.cookie:
142            header_params["Cookie"] = self.cookie
143        if header_params:
144            header_params = self.sanitize_for_serialization(header_params)
145            header_params = dict(self.parameters_to_tuples(header_params, collection_formats))
146
147        # path parameters
148        if path_params:
149            path_params = self.sanitize_for_serialization(path_params)
150            path_params = self.parameters_to_tuples(path_params, collection_formats)
151            for k, v in path_params:
152                # specified safe chars, encode everything
153                resource_path = resource_path.replace("{%s}" % k, quote(str(v), safe=config.safe_chars_for_path_param))
154
155        # query parameters
156        if query_params:
157            query_params = self.sanitize_for_serialization(query_params)
158            query_params = self.parameters_to_tuples(query_params, collection_formats)
159
160        # post parameters
161        if post_params or files:
162            post_params = post_params if post_params else []
163            post_params = self.sanitize_for_serialization(post_params)
164            post_params = self.parameters_to_tuples(post_params, collection_formats)
165            post_params.extend(self.files_parameters(files))
166            if header_params["Content-Type"].startswith("multipart"):
167                post_params = self.parameters_to_multipart(post_params, (dict))
168
169        # body
170        if body:
171            body = self.sanitize_for_serialization(body)
172
173        # auth setting
174        self.update_params_for_auth(header_params, query_params, auth_settings, resource_path, method, body)
175
176        # request url
177        if _host is None:
178            url = self.configuration.host + resource_path
179        else:
180            # use server/host defined in path or operation instead
181            url = _host + resource_path
182
183        try:
184            # perform request and return response
185            response_data = self.request(
186                method,
187                url,
188                query_params=query_params,
189                headers=header_params,
190                post_params=post_params,
191                body=body,
192                _preload_content=_preload_content,
193                _request_timeout=_request_timeout,
194            )
195        except ApiException as e:
196            e.body = e.body.decode("utf-8")
197            raise e
198
199        self.last_response = response_data
200
201        return_data = response_data
202
203        if not _preload_content:
204            return return_data
205            return return_data
206
207        # deserialize response data
208        if response_type:
209            if response_type != (file_type,):
210                encoding = "utf-8"
211                content_type = response_data.getheader("content-type")
212                if content_type is not None:
213                    match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type)
214                    if match:
215                        encoding = match.group(1)
216                response_data.data = response_data.data.decode(encoding)
217
218            return_data = self.deserialize(response_data, response_type, _check_type)
219        else:
220            return_data = None
221
222        if _return_http_data_only:
223            return return_data
224        else:
225            return (return_data, response_data.status, response_data.getheaders())
226
227    def parameters_to_multipart(self, params, collection_types):
228        """Get parameters as list of tuples, formatting as json if value is collection_types
229
230        :param params: Parameters as list of two-tuples
231        :param dict collection_types: Parameter collection types
232        :return: Parameters as list of tuple or urllib3.fields.RequestField
233        """
234        new_params = []
235        if collection_types is None:
236            collection_types = dict
237        for k, v in params.items() if isinstance(params, dict) else params:  # noqa: E501
238            if isinstance(v, collection_types):  # v is instance of collection_type, formatting as application/json
239                v = json.dumps(v, ensure_ascii=False).encode("utf-8")
240                field = RequestField(k, v)
241                field.make_multipart(content_type="application/json; charset=utf-8")
242                new_params.append(field)
243            else:
244                new_params.append((k, v))
245        return new_params
246
247    @classmethod
248    def sanitize_for_serialization(cls, obj):
249        """Prepares data for transmission before it is sent with the rest client
250        If obj is None, return None.
251        If obj is str, int, long, float, bool, return directly.
252        If obj is datetime.datetime, datetime.date
253            convert to string in iso8601 format.
254        If obj is list, sanitize each element in the list.
255        If obj is dict, return the dict.
256        If obj is OpenAPI model, return the properties dict.
257        If obj is io.IOBase, return the bytes
258        :param obj: The data to serialize.
259        :return: The serialized form of data.
260        """
261        if isinstance(obj, (ModelNormal, ModelComposed)):
262            return {key: cls.sanitize_for_serialization(val) for key, val in model_to_dict(obj, serialize=True).items()}
263        elif isinstance(obj, io.IOBase):
264            return cls.get_file_data_and_close_file(obj)
265        elif isinstance(obj, (str, int, float, none_type, bool)):
266            return obj
267        elif isinstance(obj, (datetime, date)):
268            return obj.isoformat()
269        elif isinstance(obj, ModelSimple):
270            return cls.sanitize_for_serialization(obj.value)
271        elif isinstance(obj, (list, tuple)):
272            return [cls.sanitize_for_serialization(item) for item in obj]
273        if isinstance(obj, dict):
274            return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()}
275        raise ApiValueError("Unable to prepare type {} for serialization".format(obj.__class__.__name__))
276
277    def deserialize(self, response, response_type, _check_type):
278        """Deserializes response into an object.
279
280        :param response: RESTResponse object to be deserialized.
281        :param response_type: For the response, a tuple containing:
282            valid classes
283            a list containing valid classes (for list schemas)
284            a dict containing a tuple of valid classes as the value
285            Example values:
286            (str,)
287            (Pet,)
288            (float, none_type)
289            ([int, none_type],)
290            ({str: (bool, str, int, float, date, datetime, str, none_type)},)
291        :param _check_type: boolean, whether to check the types of the data
292            received from the server
293        :type _check_type: bool
294
295        :return: deserialized object.
296        """
297        # handle file downloading
298        # save response body into a tmp file and return the instance
299        if response_type == (file_type,):
300            content_disposition = response.getheader("Content-Disposition")
301            return deserialize_file(response.data, self.configuration, content_disposition=content_disposition)
302
303        # fetch data from response object
304        try:
305            received_data = json.loads(response.data)
306        except ValueError:
307            received_data = response.data
308
309        # store our data under the key of 'received_data' so users have some
310        # context if they are deserializing a string and the data type is wrong
311        deserialized_data = validate_and_convert_types(
312            received_data, response_type, ["received_data"], True, _check_type, configuration=self.configuration
313        )
314        return deserialized_data
315
316    def call_api(
317        self,
318        resource_path: str,
319        method: str,
320        path_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
321        query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
322        header_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
323        body: typing.Optional[typing.Any] = None,
324        post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
325        files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None,
326        response_type: typing.Optional[typing.Tuple[typing.Any]] = None,
327        auth_settings: typing.Optional[typing.List[str]] = None,
328        async_req: typing.Optional[bool] = None,
329        _return_http_data_only: typing.Optional[bool] = None,
330        collection_formats: typing.Optional[typing.Dict[str, str]] = None,
331        _preload_content: bool = True,
332        _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None,
333        _host: typing.Optional[str] = None,
334        _check_type: typing.Optional[bool] = None,
335    ):
336        """Makes the HTTP request (synchronous) and returns deserialized data.
337
338        To make an async_req request, set the async_req parameter.
339
340        :param resource_path: Path to method endpoint.
341        :param method: Method to call.
342        :param path_params: Path parameters in the url.
343        :param query_params: Query parameters in the url.
344        :param header_params: Header parameters to be
345            placed in the request header.
346        :param body: Request body.
347        :param post_params dict: Request post form parameters,
348            for `application/x-www-form-urlencoded`, `multipart/form-data`.
349        :param auth_settings list: Auth Settings names for the request.
350        :param response_type: For the response, a tuple containing:
351            valid classes
352            a list containing valid classes (for list schemas)
353            a dict containing a tuple of valid classes as the value
354            Example values:
355            (str,)
356            (Pet,)
357            (float, none_type)
358            ([int, none_type],)
359            ({str: (bool, str, int, float, date, datetime, str, none_type)},)
360        :param files: key -> field name, value -> a list of open file
361            objects for `multipart/form-data`.
362        :type files: dict
363        :param async_req bool: execute request asynchronously
364        :type async_req: bool, optional
365        :param _return_http_data_only: response data without head status code
366                                       and headers
367        :type _return_http_data_only: bool, optional
368        :param collection_formats: dict of collection formats for path, query,
369            header, and post parameters.
370        :type collection_formats: dict, optional
371        :param _preload_content: if False, the urllib3.HTTPResponse object will
372                                 be returned without reading/decoding response
373                                 data. Default is True.
374        :type _preload_content: bool, optional
375        :param _request_timeout: timeout setting for this request. If one
376                                 number provided, it will be total request
377                                 timeout. It can also be a pair (tuple) of
378                                 (connection, read) timeouts.
379        :param _check_type: boolean describing if the data back from the server
380            should have its type checked.
381        :type _check_type: bool, optional
382        :return:
383            If async_req parameter is True,
384            the request will be called asynchronously.
385            The method will return the request thread.
386            If parameter async_req is False or missing,
387            then the method will return the response directly.
388        """
389        if not async_req:
390            return self.__call_api(
391                resource_path,
392                method,
393                path_params,
394                query_params,
395                header_params,
396                body,
397                post_params,
398                files,
399                response_type,
400                auth_settings,
401                _return_http_data_only,
402                collection_formats,
403                _preload_content,
404                _request_timeout,
405                _host,
406                _check_type,
407            )
408
409        return self.pool.apply_async(
410            self.__call_api,
411            (
412                resource_path,
413                method,
414                path_params,
415                query_params,
416                header_params,
417                body,
418                post_params,
419                files,
420                response_type,
421                auth_settings,
422                _return_http_data_only,
423                collection_formats,
424                _preload_content,
425                _request_timeout,
426                _host,
427                _check_type,
428            ),
429        )
430
431    def request(
432        self,
433        method,
434        url,
435        query_params=None,
436        headers=None,
437        post_params=None,
438        body=None,
439        _preload_content=True,
440        _request_timeout=None,
441    ):
442        """Makes the HTTP request using RESTClient."""
443        if method == "GET":
444            return self.rest_client.GET(
445                url,
446                query_params=query_params,
447                _preload_content=_preload_content,
448                _request_timeout=_request_timeout,
449                headers=headers,
450            )
451        elif method == "HEAD":
452            return self.rest_client.HEAD(
453                url,
454                query_params=query_params,
455                _preload_content=_preload_content,
456                _request_timeout=_request_timeout,
457                headers=headers,
458            )
459        elif method == "OPTIONS":
460            return self.rest_client.OPTIONS(
461                url,
462                query_params=query_params,
463                headers=headers,
464                post_params=post_params,
465                _preload_content=_preload_content,
466                _request_timeout=_request_timeout,
467                body=body,
468            )
469        elif method == "POST":
470            return self.rest_client.POST(
471                url,
472                query_params=query_params,
473                headers=headers,
474                post_params=post_params,
475                _preload_content=_preload_content,
476                _request_timeout=_request_timeout,
477                body=body,
478            )
479        elif method == "PUT":
480            return self.rest_client.PUT(
481                url,
482                query_params=query_params,
483                headers=headers,
484                post_params=post_params,
485                _preload_content=_preload_content,
486                _request_timeout=_request_timeout,
487                body=body,
488            )
489        elif method == "PATCH":
490            return self.rest_client.PATCH(
491                url,
492                query_params=query_params,
493                headers=headers,
494                post_params=post_params,
495                _preload_content=_preload_content,
496                _request_timeout=_request_timeout,
497                body=body,
498            )
499        elif method == "DELETE":
500            return self.rest_client.DELETE(
501                url,
502                query_params=query_params,
503                headers=headers,
504                _preload_content=_preload_content,
505                _request_timeout=_request_timeout,
506                body=body,
507            )
508        else:
509            raise ApiValueError("http method must be `GET`, `HEAD`, `OPTIONS`," " `POST`, `PATCH`, `PUT` or `DELETE`.")
510
511    def parameters_to_tuples(self, params, collection_formats):
512        """Get parameters as list of tuples, formatting collections.
513
514        :param params: Parameters as dict or list of two-tuples
515        :param dict collection_formats: Parameter collection formats
516        :return: Parameters as list of tuples, collections formatted
517        """
518        new_params = []
519        if collection_formats is None:
520            collection_formats = {}
521        for k, v in params.items() if isinstance(params, dict) else params:  # noqa: E501
522            if k in collection_formats:
523                collection_format = collection_formats[k]
524                if collection_format == "multi":
525                    new_params.extend((k, value) for value in v)
526                else:
527                    if collection_format == "ssv":
528                        delimiter = " "
529                    elif collection_format == "tsv":
530                        delimiter = "\t"
531                    elif collection_format == "pipes":
532                        delimiter = "|"
533                    else:  # csv is the default
534                        delimiter = ","
535                    new_params.append((k, delimiter.join(str(value) for value in v)))
536            else:
537                new_params.append((k, v))
538        return new_params
539
540    @staticmethod
541    def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes:
542        file_data = file_instance.read()
543        file_instance.close()
544        return file_data
545
546    def files_parameters(self, files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None):
547        """Builds form parameters.
548
549        :param files: None or a dict with key=param_name and
550            value is a list of open file objects
551        :return: List of tuples of form parameters with file data
552        """
553        if files is None:
554            return []
555
556        params = []
557        for param_name, file_instances in files.items():
558            if file_instances is None:
559                # if the file field is nullable, skip None values
560                continue
561            for file_instance in file_instances:
562                if file_instance is None:
563                    # if the file field is nullable, skip None values
564                    continue
565                if file_instance.closed is True:
566                    raise ApiValueError(
567                        "Cannot read a closed file. The passed in file_type " "for %s must be open." % param_name
568                    )
569                filename = os.path.basename(file_instance.name)
570                filedata = self.get_file_data_and_close_file(file_instance)
571                mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
572                params.append(tuple([param_name, tuple([filename, filedata, mimetype])]))
573
574        return params
575
576    def select_header_accept(self, accepts):
577        """Returns `Accept` based on an array of accepts provided.
578
579        :param accepts: List of headers.
580        :return: Accept (e.g. application/json).
581        """
582        if not accepts:
583            return
584
585        accepts = [x.lower() for x in accepts]
586
587        if "application/json" in accepts:
588            return "application/json"
589        else:
590            return ", ".join(accepts)
591
592    def select_header_content_type(self, content_types):
593        """Returns `Content-Type` based on an array of content_types provided.
594
595        :param content_types: List of content-types.
596        :return: Content-Type (e.g. application/json).
597        """
598        if not content_types:
599            return "application/json"
600
601        content_types = [x.lower() for x in content_types]
602
603        if "application/json" in content_types or "*/*" in content_types:
604            return "application/json"
605        else:
606            return content_types[0]
607
608    def update_params_for_auth(self, headers, querys, auth_settings, resource_path, method, body):
609        """Updates header and query params based on authentication setting.
610
611        :param headers: Header parameters dict to be updated.
612        :param querys: Query parameters tuple list to be updated.
613        :param auth_settings: Authentication setting identifiers list.
614        :param resource_path: A string representation of the HTTP request resource path.
615        :param method: A string representation of the HTTP request method.
616        :param body: A object representing the body of the HTTP request.
617            The object type is the return value of _encoder.default().
618        """
619        if not auth_settings:
620            return
621
622        for auth in auth_settings:
623            auth_setting = self.configuration.auth_settings().get(auth)
624            if auth_setting:
625                if auth_setting["in"] == "cookie":
626                    headers["Cookie"] = auth_setting["value"]
627                elif auth_setting["in"] == "header":
628                    if auth_setting["type"] != "http-signature":
629                        headers[auth_setting["key"]] = auth_setting["value"]
630                elif auth_setting["in"] == "query":
631                    querys.append((auth_setting["key"], auth_setting["value"]))
632                else:
633                    raise ApiValueError("Authentication token must be in `query` or `header`")
634
635
636class Endpoint(object):
637    def __init__(self, settings=None, params_map=None, root_map=None, headers_map=None, api_client=None, callable=None):
638        """Creates an endpoint
639
640        Args:
641            settings (dict): see below key value pairs
642                'response_type' (tuple/None): response type
643                'auth' (list): a list of auth type keys
644                'endpoint_path' (str): the endpoint path
645                'operation_id' (str): endpoint string identifier
646                'http_method' (str): POST/PUT/PATCH/GET etc
647                'servers' (list): list of str servers that this endpoint is at
648            params_map (dict): see below key value pairs
649                'all' (list): list of str endpoint parameter names
650                'required' (list): list of required parameter names
651                'nullable' (list): list of nullable parameter names
652                'enum' (list): list of parameters with enum values
653                'validation' (list): list of parameters with validations
654            root_map
655                'validations' (dict): the dict mapping endpoint parameter tuple
656                    paths to their validation dictionaries
657                'allowed_values' (dict): the dict mapping endpoint parameter
658                    tuple paths to their allowed_values (enum) dictionaries
659                'openapi_types' (dict): param_name to openapi type
660                'attribute_map' (dict): param_name to camelCase name
661                'location_map' (dict): param_name to  'body', 'file', 'form',
662                    'header', 'path', 'query'
663                collection_format_map (dict): param_name to `csv` etc.
664            headers_map (dict): see below key value pairs
665                'accept' (list): list of Accept header strings
666                'content_type' (list): list of Content-Type header strings
667            api_client (ApiClient) api client instance
668            callable (function): the function which is invoked when the
669                Endpoint is called
670        """
671        self.settings = settings
672        self.params_map = params_map
673        self.params_map["all"].extend(
674            [
675                "async_req",
676                "_host_index",
677                "_preload_content",
678                "_request_timeout",
679                "_return_http_data_only",
680                "_check_input_type",
681                "_check_return_type",
682            ]
683        )
684        self.params_map["nullable"].extend(["_request_timeout"])
685        self.validations = root_map["validations"]
686        self.allowed_values = root_map["allowed_values"]
687        self.openapi_types = root_map["openapi_types"]
688        extra_types = {
689            "async_req": (bool,),
690            "_host_index": (none_type, int),
691            "_preload_content": (bool,),
692            "_request_timeout": (none_type, float, (float,), [float], int, (int,), [int]),
693            "_return_http_data_only": (bool,),
694            "_check_input_type": (bool,),
695            "_check_return_type": (bool,),
696        }
697        self.openapi_types.update(extra_types)
698        self.attribute_map = root_map["attribute_map"]
699        self.location_map = root_map["location_map"]
700        self.collection_format_map = root_map["collection_format_map"]
701        self.headers_map = headers_map
702        self.api_client = api_client
703        self.callable = callable
704
705    def __validate_inputs(self, kwargs):
706        for param in self.params_map["enum"]:
707            if param in kwargs:
708                check_allowed_values(self.allowed_values, (param,), kwargs[param])
709
710        for param in self.params_map["validation"]:
711            if param in kwargs:
712                check_validations(
713                    self.validations, (param,), kwargs[param], configuration=self.api_client.configuration
714                )
715
716        if kwargs["_check_input_type"] is False:
717            return
718
719        for key, value in kwargs.items():
720            fixed_val = validate_and_convert_types(
721                value,
722                self.openapi_types[key],
723                [key],
724                False,
725                kwargs["_check_input_type"],
726                configuration=self.api_client.configuration,
727            )
728            kwargs[key] = fixed_val
729
730    def __gather_params(self, kwargs):
731        params = {"body": None, "collection_format": {}, "file": {}, "form": [], "header": {}, "path": {}, "query": []}
732
733        for param_name, param_value in kwargs.items():
734            param_location = self.location_map.get(param_name)
735            if param_location is None:
736                continue
737            if param_location:
738                if param_location == "body":
739                    params["body"] = param_value
740                    continue
741                base_name = self.attribute_map[param_name]
742                if param_location == "form" and self.openapi_types[param_name] == (file_type,):
743                    params["file"][param_name] = [param_value]
744                elif param_location == "form" and self.openapi_types[param_name] == ([file_type],):
745                    # param_value is already a list
746                    params["file"][param_name] = param_value
747                elif param_location in {"form", "query"}:
748                    param_value_full = (base_name, param_value)
749                    params[param_location].append(param_value_full)
750                if param_location not in {"form", "query"}:
751                    params[param_location][base_name] = param_value
752                collection_format = self.collection_format_map.get(param_name)
753                if collection_format:
754                    params["collection_format"][base_name] = collection_format
755
756        return params
757
758    def __call__(self, *args, **kwargs):
759        """This method is invoked when endpoints are called
760        Example:
761
762        api_instance = IndexOperationsApi()
763        api_instance.configure_index  # this is an instance of the class Endpoint
764        api_instance.configure_index()  # this invokes api_instance.configure_index.__call__()
765        which then invokes the callable functions stored in that endpoint at
766        api_instance.configure_index.callable or self.callable in this class
767
768        """
769        return self.callable(self, *args, **kwargs)
770
771    def call_with_http_info(self, **kwargs):
772        try:
773            index = (
774                self.api_client.configuration.server_operation_index.get(
775                    self.settings["operation_id"], self.api_client.configuration.server_index
776                )
777                if kwargs["_host_index"] is None
778                else kwargs["_host_index"]
779            )
780            server_variables = self.api_client.configuration.server_operation_variables.get(
781                self.settings["operation_id"], self.api_client.configuration.server_variables
782            )
783            _host = self.api_client.configuration.get_host_from_settings(
784                index, variables=server_variables, servers=self.settings["servers"]
785            )
786        except IndexError:
787            if self.settings["servers"]:
788                raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(self.settings["servers"]))
789            _host = None
790
791        for key, value in kwargs.items():
792            if key not in self.params_map["all"]:
793                raise ApiTypeError(
794                    "Got an unexpected parameter '%s'" " to method `%s`" % (key, self.settings["operation_id"])
795                )
796            # only throw this nullable ApiValueError if _check_input_type
797            # is False, if _check_input_type==True we catch this case
798            # in self.__validate_inputs
799            if key not in self.params_map["nullable"] and value is None and kwargs["_check_input_type"] is False:
800                raise ApiValueError(
801                    "Value may not be None for non-nullable parameter `%s`"
802                    " when calling `%s`" % (key, self.settings["operation_id"])
803                )
804
805        for key in self.params_map["required"]:
806            if key not in kwargs.keys():
807                raise ApiValueError(
808                    "Missing the required parameter `%s` when calling " "`%s`" % (key, self.settings["operation_id"])
809                )
810
811        self.__validate_inputs(kwargs)
812
813        params = self.__gather_params(kwargs)
814
815        accept_headers_list = self.headers_map["accept"]
816        if accept_headers_list:
817            params["header"]["Accept"] = self.api_client.select_header_accept(accept_headers_list)
818
819        content_type_headers_list = self.headers_map["content_type"]
820        if content_type_headers_list:
821            header_list = self.api_client.select_header_content_type(content_type_headers_list)
822            params["header"]["Content-Type"] = header_list
823
824        return self.api_client.call_api(
825            self.settings["endpoint_path"],
826            self.settings["http_method"],
827            params["path"],
828            params["query"],
829            params["header"],
830            body=params["body"],
831            post_params=params["form"],
832            files=params["file"],
833            response_type=self.settings["response_type"],
834            auth_settings=self.settings["auth"],
835            async_req=kwargs["async_req"],
836            _check_type=kwargs["_check_return_type"],
837            _return_http_data_only=kwargs["_return_http_data_only"],
838            _preload_content=kwargs["_preload_content"],
839            _request_timeout=kwargs["_request_timeout"],
840            _host=_host,
841            collection_formats=params["collection_format"],
842        )
class ApiClient:
 44class ApiClient(object):
 45    """Generic API client for OpenAPI client library builds.
 46
 47    OpenAPI generic API client. This client handles the client-
 48    server communication, and is invariant across implementations. Specifics of
 49    the methods and models for each application are generated from the OpenAPI
 50    templates.
 51
 52    NOTE: This class is auto generated by OpenAPI Generator.
 53    Ref: https://openapi-generator.tech
 54    Do not edit the class manually.
 55
 56    :param configuration: .Configuration object for this client
 57    :param header_name: a header to pass when making calls to the API.
 58    :param header_value: a header value to pass when making calls to
 59        the API.
 60    :param cookie: a cookie to include in the header when making calls
 61        to the API
 62    :param pool_threads: The number of threads to use for async requests
 63        to the API. More threads means more concurrent API requests.
 64    """
 65
 66    _pool = None
 67
 68    def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None, pool_threads=1):
 69        if configuration is None:
 70            configuration = Configuration.get_default_copy()
 71        self.configuration = configuration
 72        self.pool_threads = pool_threads
 73
 74        self.rest_client = rest.RESTClientObject(configuration)
 75        self.default_headers = {}
 76        if header_name is not None:
 77            self.default_headers[header_name] = header_value
 78        self.cookie = cookie
 79        # Set default User-Agent.
 80        self.user_agent = "OpenAPI-Generator/1.0.0/python"
 81
 82    def __enter__(self):
 83        return self
 84
 85    def __exit__(self, exc_type, exc_value, traceback):
 86        self.close()
 87
 88    def close(self):
 89        if self._pool:
 90            self._pool.close()
 91            self._pool.join()
 92            self._pool = None
 93            if hasattr(atexit, "unregister"):
 94                atexit.unregister(self.close)
 95
 96    @property
 97    def pool(self):
 98        """Create thread pool on first request
 99        avoids instantiating unused threadpool for blocking clients.
100        """
101        if self._pool is None:
102            atexit.register(self.close)
103            self._pool = ThreadPool(self.pool_threads)
104        return self._pool
105
106    @property
107    def user_agent(self):
108        """User agent for this API client"""
109        return self.default_headers["User-Agent"]
110
111    @user_agent.setter
112    def user_agent(self, value):
113        self.default_headers["User-Agent"] = value
114
115    def set_default_header(self, header_name, header_value):
116        self.default_headers[header_name] = header_value
117
118    def __call_api(
119        self,
120        resource_path: str,
121        method: str,
122        path_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
123        query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
124        header_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
125        body: typing.Optional[typing.Any] = None,
126        post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
127        files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None,
128        response_type: typing.Optional[typing.Tuple[typing.Any]] = None,
129        auth_settings: typing.Optional[typing.List[str]] = None,
130        _return_http_data_only: typing.Optional[bool] = None,
131        collection_formats: typing.Optional[typing.Dict[str, str]] = None,
132        _preload_content: bool = True,
133        _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None,
134        _host: typing.Optional[str] = None,
135        _check_type: typing.Optional[bool] = None,
136    ):
137        config = self.configuration
138
139        # header parameters
140        header_params = header_params or {}
141        header_params.update(self.default_headers)
142        if self.cookie:
143            header_params["Cookie"] = self.cookie
144        if header_params:
145            header_params = self.sanitize_for_serialization(header_params)
146            header_params = dict(self.parameters_to_tuples(header_params, collection_formats))
147
148        # path parameters
149        if path_params:
150            path_params = self.sanitize_for_serialization(path_params)
151            path_params = self.parameters_to_tuples(path_params, collection_formats)
152            for k, v in path_params:
153                # specified safe chars, encode everything
154                resource_path = resource_path.replace("{%s}" % k, quote(str(v), safe=config.safe_chars_for_path_param))
155
156        # query parameters
157        if query_params:
158            query_params = self.sanitize_for_serialization(query_params)
159            query_params = self.parameters_to_tuples(query_params, collection_formats)
160
161        # post parameters
162        if post_params or files:
163            post_params = post_params if post_params else []
164            post_params = self.sanitize_for_serialization(post_params)
165            post_params = self.parameters_to_tuples(post_params, collection_formats)
166            post_params.extend(self.files_parameters(files))
167            if header_params["Content-Type"].startswith("multipart"):
168                post_params = self.parameters_to_multipart(post_params, (dict))
169
170        # body
171        if body:
172            body = self.sanitize_for_serialization(body)
173
174        # auth setting
175        self.update_params_for_auth(header_params, query_params, auth_settings, resource_path, method, body)
176
177        # request url
178        if _host is None:
179            url = self.configuration.host + resource_path
180        else:
181            # use server/host defined in path or operation instead
182            url = _host + resource_path
183
184        try:
185            # perform request and return response
186            response_data = self.request(
187                method,
188                url,
189                query_params=query_params,
190                headers=header_params,
191                post_params=post_params,
192                body=body,
193                _preload_content=_preload_content,
194                _request_timeout=_request_timeout,
195            )
196        except ApiException as e:
197            e.body = e.body.decode("utf-8")
198            raise e
199
200        self.last_response = response_data
201
202        return_data = response_data
203
204        if not _preload_content:
205            return return_data
206            return return_data
207
208        # deserialize response data
209        if response_type:
210            if response_type != (file_type,):
211                encoding = "utf-8"
212                content_type = response_data.getheader("content-type")
213                if content_type is not None:
214                    match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type)
215                    if match:
216                        encoding = match.group(1)
217                response_data.data = response_data.data.decode(encoding)
218
219            return_data = self.deserialize(response_data, response_type, _check_type)
220        else:
221            return_data = None
222
223        if _return_http_data_only:
224            return return_data
225        else:
226            return (return_data, response_data.status, response_data.getheaders())
227
228    def parameters_to_multipart(self, params, collection_types):
229        """Get parameters as list of tuples, formatting as json if value is collection_types
230
231        :param params: Parameters as list of two-tuples
232        :param dict collection_types: Parameter collection types
233        :return: Parameters as list of tuple or urllib3.fields.RequestField
234        """
235        new_params = []
236        if collection_types is None:
237            collection_types = dict
238        for k, v in params.items() if isinstance(params, dict) else params:  # noqa: E501
239            if isinstance(v, collection_types):  # v is instance of collection_type, formatting as application/json
240                v = json.dumps(v, ensure_ascii=False).encode("utf-8")
241                field = RequestField(k, v)
242                field.make_multipart(content_type="application/json; charset=utf-8")
243                new_params.append(field)
244            else:
245                new_params.append((k, v))
246        return new_params
247
248    @classmethod
249    def sanitize_for_serialization(cls, obj):
250        """Prepares data for transmission before it is sent with the rest client
251        If obj is None, return None.
252        If obj is str, int, long, float, bool, return directly.
253        If obj is datetime.datetime, datetime.date
254            convert to string in iso8601 format.
255        If obj is list, sanitize each element in the list.
256        If obj is dict, return the dict.
257        If obj is OpenAPI model, return the properties dict.
258        If obj is io.IOBase, return the bytes
259        :param obj: The data to serialize.
260        :return: The serialized form of data.
261        """
262        if isinstance(obj, (ModelNormal, ModelComposed)):
263            return {key: cls.sanitize_for_serialization(val) for key, val in model_to_dict(obj, serialize=True).items()}
264        elif isinstance(obj, io.IOBase):
265            return cls.get_file_data_and_close_file(obj)
266        elif isinstance(obj, (str, int, float, none_type, bool)):
267            return obj
268        elif isinstance(obj, (datetime, date)):
269            return obj.isoformat()
270        elif isinstance(obj, ModelSimple):
271            return cls.sanitize_for_serialization(obj.value)
272        elif isinstance(obj, (list, tuple)):
273            return [cls.sanitize_for_serialization(item) for item in obj]
274        if isinstance(obj, dict):
275            return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()}
276        raise ApiValueError("Unable to prepare type {} for serialization".format(obj.__class__.__name__))
277
278    def deserialize(self, response, response_type, _check_type):
279        """Deserializes response into an object.
280
281        :param response: RESTResponse object to be deserialized.
282        :param response_type: For the response, a tuple containing:
283            valid classes
284            a list containing valid classes (for list schemas)
285            a dict containing a tuple of valid classes as the value
286            Example values:
287            (str,)
288            (Pet,)
289            (float, none_type)
290            ([int, none_type],)
291            ({str: (bool, str, int, float, date, datetime, str, none_type)},)
292        :param _check_type: boolean, whether to check the types of the data
293            received from the server
294        :type _check_type: bool
295
296        :return: deserialized object.
297        """
298        # handle file downloading
299        # save response body into a tmp file and return the instance
300        if response_type == (file_type,):
301            content_disposition = response.getheader("Content-Disposition")
302            return deserialize_file(response.data, self.configuration, content_disposition=content_disposition)
303
304        # fetch data from response object
305        try:
306            received_data = json.loads(response.data)
307        except ValueError:
308            received_data = response.data
309
310        # store our data under the key of 'received_data' so users have some
311        # context if they are deserializing a string and the data type is wrong
312        deserialized_data = validate_and_convert_types(
313            received_data, response_type, ["received_data"], True, _check_type, configuration=self.configuration
314        )
315        return deserialized_data
316
317    def call_api(
318        self,
319        resource_path: str,
320        method: str,
321        path_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
322        query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
323        header_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
324        body: typing.Optional[typing.Any] = None,
325        post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
326        files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None,
327        response_type: typing.Optional[typing.Tuple[typing.Any]] = None,
328        auth_settings: typing.Optional[typing.List[str]] = None,
329        async_req: typing.Optional[bool] = None,
330        _return_http_data_only: typing.Optional[bool] = None,
331        collection_formats: typing.Optional[typing.Dict[str, str]] = None,
332        _preload_content: bool = True,
333        _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None,
334        _host: typing.Optional[str] = None,
335        _check_type: typing.Optional[bool] = None,
336    ):
337        """Makes the HTTP request (synchronous) and returns deserialized data.
338
339        To make an async_req request, set the async_req parameter.
340
341        :param resource_path: Path to method endpoint.
342        :param method: Method to call.
343        :param path_params: Path parameters in the url.
344        :param query_params: Query parameters in the url.
345        :param header_params: Header parameters to be
346            placed in the request header.
347        :param body: Request body.
348        :param post_params dict: Request post form parameters,
349            for `application/x-www-form-urlencoded`, `multipart/form-data`.
350        :param auth_settings list: Auth Settings names for the request.
351        :param response_type: For the response, a tuple containing:
352            valid classes
353            a list containing valid classes (for list schemas)
354            a dict containing a tuple of valid classes as the value
355            Example values:
356            (str,)
357            (Pet,)
358            (float, none_type)
359            ([int, none_type],)
360            ({str: (bool, str, int, float, date, datetime, str, none_type)},)
361        :param files: key -> field name, value -> a list of open file
362            objects for `multipart/form-data`.
363        :type files: dict
364        :param async_req bool: execute request asynchronously
365        :type async_req: bool, optional
366        :param _return_http_data_only: response data without head status code
367                                       and headers
368        :type _return_http_data_only: bool, optional
369        :param collection_formats: dict of collection formats for path, query,
370            header, and post parameters.
371        :type collection_formats: dict, optional
372        :param _preload_content: if False, the urllib3.HTTPResponse object will
373                                 be returned without reading/decoding response
374                                 data. Default is True.
375        :type _preload_content: bool, optional
376        :param _request_timeout: timeout setting for this request. If one
377                                 number provided, it will be total request
378                                 timeout. It can also be a pair (tuple) of
379                                 (connection, read) timeouts.
380        :param _check_type: boolean describing if the data back from the server
381            should have its type checked.
382        :type _check_type: bool, optional
383        :return:
384            If async_req parameter is True,
385            the request will be called asynchronously.
386            The method will return the request thread.
387            If parameter async_req is False or missing,
388            then the method will return the response directly.
389        """
390        if not async_req:
391            return self.__call_api(
392                resource_path,
393                method,
394                path_params,
395                query_params,
396                header_params,
397                body,
398                post_params,
399                files,
400                response_type,
401                auth_settings,
402                _return_http_data_only,
403                collection_formats,
404                _preload_content,
405                _request_timeout,
406                _host,
407                _check_type,
408            )
409
410        return self.pool.apply_async(
411            self.__call_api,
412            (
413                resource_path,
414                method,
415                path_params,
416                query_params,
417                header_params,
418                body,
419                post_params,
420                files,
421                response_type,
422                auth_settings,
423                _return_http_data_only,
424                collection_formats,
425                _preload_content,
426                _request_timeout,
427                _host,
428                _check_type,
429            ),
430        )
431
432    def request(
433        self,
434        method,
435        url,
436        query_params=None,
437        headers=None,
438        post_params=None,
439        body=None,
440        _preload_content=True,
441        _request_timeout=None,
442    ):
443        """Makes the HTTP request using RESTClient."""
444        if method == "GET":
445            return self.rest_client.GET(
446                url,
447                query_params=query_params,
448                _preload_content=_preload_content,
449                _request_timeout=_request_timeout,
450                headers=headers,
451            )
452        elif method == "HEAD":
453            return self.rest_client.HEAD(
454                url,
455                query_params=query_params,
456                _preload_content=_preload_content,
457                _request_timeout=_request_timeout,
458                headers=headers,
459            )
460        elif method == "OPTIONS":
461            return self.rest_client.OPTIONS(
462                url,
463                query_params=query_params,
464                headers=headers,
465                post_params=post_params,
466                _preload_content=_preload_content,
467                _request_timeout=_request_timeout,
468                body=body,
469            )
470        elif method == "POST":
471            return self.rest_client.POST(
472                url,
473                query_params=query_params,
474                headers=headers,
475                post_params=post_params,
476                _preload_content=_preload_content,
477                _request_timeout=_request_timeout,
478                body=body,
479            )
480        elif method == "PUT":
481            return self.rest_client.PUT(
482                url,
483                query_params=query_params,
484                headers=headers,
485                post_params=post_params,
486                _preload_content=_preload_content,
487                _request_timeout=_request_timeout,
488                body=body,
489            )
490        elif method == "PATCH":
491            return self.rest_client.PATCH(
492                url,
493                query_params=query_params,
494                headers=headers,
495                post_params=post_params,
496                _preload_content=_preload_content,
497                _request_timeout=_request_timeout,
498                body=body,
499            )
500        elif method == "DELETE":
501            return self.rest_client.DELETE(
502                url,
503                query_params=query_params,
504                headers=headers,
505                _preload_content=_preload_content,
506                _request_timeout=_request_timeout,
507                body=body,
508            )
509        else:
510            raise ApiValueError("http method must be `GET`, `HEAD`, `OPTIONS`," " `POST`, `PATCH`, `PUT` or `DELETE`.")
511
512    def parameters_to_tuples(self, params, collection_formats):
513        """Get parameters as list of tuples, formatting collections.
514
515        :param params: Parameters as dict or list of two-tuples
516        :param dict collection_formats: Parameter collection formats
517        :return: Parameters as list of tuples, collections formatted
518        """
519        new_params = []
520        if collection_formats is None:
521            collection_formats = {}
522        for k, v in params.items() if isinstance(params, dict) else params:  # noqa: E501
523            if k in collection_formats:
524                collection_format = collection_formats[k]
525                if collection_format == "multi":
526                    new_params.extend((k, value) for value in v)
527                else:
528                    if collection_format == "ssv":
529                        delimiter = " "
530                    elif collection_format == "tsv":
531                        delimiter = "\t"
532                    elif collection_format == "pipes":
533                        delimiter = "|"
534                    else:  # csv is the default
535                        delimiter = ","
536                    new_params.append((k, delimiter.join(str(value) for value in v)))
537            else:
538                new_params.append((k, v))
539        return new_params
540
541    @staticmethod
542    def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes:
543        file_data = file_instance.read()
544        file_instance.close()
545        return file_data
546
547    def files_parameters(self, files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None):
548        """Builds form parameters.
549
550        :param files: None or a dict with key=param_name and
551            value is a list of open file objects
552        :return: List of tuples of form parameters with file data
553        """
554        if files is None:
555            return []
556
557        params = []
558        for param_name, file_instances in files.items():
559            if file_instances is None:
560                # if the file field is nullable, skip None values
561                continue
562            for file_instance in file_instances:
563                if file_instance is None:
564                    # if the file field is nullable, skip None values
565                    continue
566                if file_instance.closed is True:
567                    raise ApiValueError(
568                        "Cannot read a closed file. The passed in file_type " "for %s must be open." % param_name
569                    )
570                filename = os.path.basename(file_instance.name)
571                filedata = self.get_file_data_and_close_file(file_instance)
572                mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
573                params.append(tuple([param_name, tuple([filename, filedata, mimetype])]))
574
575        return params
576
577    def select_header_accept(self, accepts):
578        """Returns `Accept` based on an array of accepts provided.
579
580        :param accepts: List of headers.
581        :return: Accept (e.g. application/json).
582        """
583        if not accepts:
584            return
585
586        accepts = [x.lower() for x in accepts]
587
588        if "application/json" in accepts:
589            return "application/json"
590        else:
591            return ", ".join(accepts)
592
593    def select_header_content_type(self, content_types):
594        """Returns `Content-Type` based on an array of content_types provided.
595
596        :param content_types: List of content-types.
597        :return: Content-Type (e.g. application/json).
598        """
599        if not content_types:
600            return "application/json"
601
602        content_types = [x.lower() for x in content_types]
603
604        if "application/json" in content_types or "*/*" in content_types:
605            return "application/json"
606        else:
607            return content_types[0]
608
609    def update_params_for_auth(self, headers, querys, auth_settings, resource_path, method, body):
610        """Updates header and query params based on authentication setting.
611
612        :param headers: Header parameters dict to be updated.
613        :param querys: Query parameters tuple list to be updated.
614        :param auth_settings: Authentication setting identifiers list.
615        :param resource_path: A string representation of the HTTP request resource path.
616        :param method: A string representation of the HTTP request method.
617        :param body: A object representing the body of the HTTP request.
618            The object type is the return value of _encoder.default().
619        """
620        if not auth_settings:
621            return
622
623        for auth in auth_settings:
624            auth_setting = self.configuration.auth_settings().get(auth)
625            if auth_setting:
626                if auth_setting["in"] == "cookie":
627                    headers["Cookie"] = auth_setting["value"]
628                elif auth_setting["in"] == "header":
629                    if auth_setting["type"] != "http-signature":
630                        headers[auth_setting["key"]] = auth_setting["value"]
631                elif auth_setting["in"] == "query":
632                    querys.append((auth_setting["key"], auth_setting["value"]))
633                else:
634                    raise ApiValueError("Authentication token must be in `query` or `header`")

Generic API client for OpenAPI client library builds.

OpenAPI generic API client. This client handles the client- server communication, and is invariant across implementations. Specifics of the methods and models for each application are generated from the OpenAPI templates.

NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.

Parameters
  • configuration: .Configuration object for this client
  • header_name: a header to pass when making calls to the API.
  • header_value: a header value to pass when making calls to the API.
  • cookie: a cookie to include in the header when making calls to the API
  • pool_threads: The number of threads to use for async requests to the API. More threads means more concurrent API requests.
ApiClient( configuration=None, header_name=None, header_value=None, cookie=None, pool_threads=1)
68    def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None, pool_threads=1):
69        if configuration is None:
70            configuration = Configuration.get_default_copy()
71        self.configuration = configuration
72        self.pool_threads = pool_threads
73
74        self.rest_client = rest.RESTClientObject(configuration)
75        self.default_headers = {}
76        if header_name is not None:
77            self.default_headers[header_name] = header_value
78        self.cookie = cookie
79        # Set default User-Agent.
80        self.user_agent = "OpenAPI-Generator/1.0.0/python"
configuration
pool_threads
rest_client
default_headers
cookie
user_agent

User agent for this API client

def close(self):
88    def close(self):
89        if self._pool:
90            self._pool.close()
91            self._pool.join()
92            self._pool = None
93            if hasattr(atexit, "unregister"):
94                atexit.unregister(self.close)
pool

Create thread pool on first request avoids instantiating unused threadpool for blocking clients.

def set_default_header(self, header_name, header_value):
115    def set_default_header(self, header_name, header_value):
116        self.default_headers[header_name] = header_value
def parameters_to_multipart(self, params, collection_types):
228    def parameters_to_multipart(self, params, collection_types):
229        """Get parameters as list of tuples, formatting as json if value is collection_types
230
231        :param params: Parameters as list of two-tuples
232        :param dict collection_types: Parameter collection types
233        :return: Parameters as list of tuple or urllib3.fields.RequestField
234        """
235        new_params = []
236        if collection_types is None:
237            collection_types = dict
238        for k, v in params.items() if isinstance(params, dict) else params:  # noqa: E501
239            if isinstance(v, collection_types):  # v is instance of collection_type, formatting as application/json
240                v = json.dumps(v, ensure_ascii=False).encode("utf-8")
241                field = RequestField(k, v)
242                field.make_multipart(content_type="application/json; charset=utf-8")
243                new_params.append(field)
244            else:
245                new_params.append((k, v))
246        return new_params

Get parameters as list of tuples, formatting as json if value is collection_types

Parameters
  • params: Parameters as list of two-tuples
  • dict collection_types: Parameter collection types
Returns

Parameters as list of tuple or urllib3.fields.RequestField

@classmethod
def sanitize_for_serialization(cls, obj):
248    @classmethod
249    def sanitize_for_serialization(cls, obj):
250        """Prepares data for transmission before it is sent with the rest client
251        If obj is None, return None.
252        If obj is str, int, long, float, bool, return directly.
253        If obj is datetime.datetime, datetime.date
254            convert to string in iso8601 format.
255        If obj is list, sanitize each element in the list.
256        If obj is dict, return the dict.
257        If obj is OpenAPI model, return the properties dict.
258        If obj is io.IOBase, return the bytes
259        :param obj: The data to serialize.
260        :return: The serialized form of data.
261        """
262        if isinstance(obj, (ModelNormal, ModelComposed)):
263            return {key: cls.sanitize_for_serialization(val) for key, val in model_to_dict(obj, serialize=True).items()}
264        elif isinstance(obj, io.IOBase):
265            return cls.get_file_data_and_close_file(obj)
266        elif isinstance(obj, (str, int, float, none_type, bool)):
267            return obj
268        elif isinstance(obj, (datetime, date)):
269            return obj.isoformat()
270        elif isinstance(obj, ModelSimple):
271            return cls.sanitize_for_serialization(obj.value)
272        elif isinstance(obj, (list, tuple)):
273            return [cls.sanitize_for_serialization(item) for item in obj]
274        if isinstance(obj, dict):
275            return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()}
276        raise ApiValueError("Unable to prepare type {} for serialization".format(obj.__class__.__name__))

Prepares data for transmission before it is sent with the rest client If obj is None, return None. If obj is str, int, long, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, sanitize each element in the list. If obj is dict, return the dict. If obj is OpenAPI model, return the properties dict. If obj is io.IOBase, return the bytes

Parameters
  • obj: The data to serialize.
Returns

The serialized form of data.

def deserialize(self, response, response_type, _check_type):
278    def deserialize(self, response, response_type, _check_type):
279        """Deserializes response into an object.
280
281        :param response: RESTResponse object to be deserialized.
282        :param response_type: For the response, a tuple containing:
283            valid classes
284            a list containing valid classes (for list schemas)
285            a dict containing a tuple of valid classes as the value
286            Example values:
287            (str,)
288            (Pet,)
289            (float, none_type)
290            ([int, none_type],)
291            ({str: (bool, str, int, float, date, datetime, str, none_type)},)
292        :param _check_type: boolean, whether to check the types of the data
293            received from the server
294        :type _check_type: bool
295
296        :return: deserialized object.
297        """
298        # handle file downloading
299        # save response body into a tmp file and return the instance
300        if response_type == (file_type,):
301            content_disposition = response.getheader("Content-Disposition")
302            return deserialize_file(response.data, self.configuration, content_disposition=content_disposition)
303
304        # fetch data from response object
305        try:
306            received_data = json.loads(response.data)
307        except ValueError:
308            received_data = response.data
309
310        # store our data under the key of 'received_data' so users have some
311        # context if they are deserializing a string and the data type is wrong
312        deserialized_data = validate_and_convert_types(
313            received_data, response_type, ["received_data"], True, _check_type, configuration=self.configuration
314        )
315        return deserialized_data

Deserializes response into an object.

Parameters
  • response: RESTResponse object to be deserialized.
  • response_type: For the response, a tuple containing: valid classes a list containing valid classes (for list schemas) a dict containing a tuple of valid classes as the value Example values: (str,) (Pet,) (float, none_type) ([int, none_type],) ({str: (bool, str, int, float, date, datetime, str, none_type)},)
  • _check_type: boolean, whether to check the types of the data received from the server
Returns

deserialized object.

def call_api( self, resource_path: str, method: str, path_params: Optional[Dict[str, Any]] = None, query_params: Optional[List[Tuple[str, Any]]] = None, header_params: Optional[Dict[str, Any]] = None, body: Optional[Any] = None, post_params: Optional[List[Tuple[str, Any]]] = None, files: Optional[Dict[str, List[io.IOBase]]] = None, response_type: Optional[Tuple[Any]] = None, auth_settings: Optional[List[str]] = None, async_req: Optional[bool] = None, _return_http_data_only: Optional[bool] = None, collection_formats: Optional[Dict[str, str]] = None, _preload_content: bool = True, _request_timeout: Union[int, float, Tuple, NoneType] = None, _host: Optional[str] = None, _check_type: Optional[bool] = None):
317    def call_api(
318        self,
319        resource_path: str,
320        method: str,
321        path_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
322        query_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
323        header_params: typing.Optional[typing.Dict[str, typing.Any]] = None,
324        body: typing.Optional[typing.Any] = None,
325        post_params: typing.Optional[typing.List[typing.Tuple[str, typing.Any]]] = None,
326        files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None,
327        response_type: typing.Optional[typing.Tuple[typing.Any]] = None,
328        auth_settings: typing.Optional[typing.List[str]] = None,
329        async_req: typing.Optional[bool] = None,
330        _return_http_data_only: typing.Optional[bool] = None,
331        collection_formats: typing.Optional[typing.Dict[str, str]] = None,
332        _preload_content: bool = True,
333        _request_timeout: typing.Optional[typing.Union[int, float, typing.Tuple]] = None,
334        _host: typing.Optional[str] = None,
335        _check_type: typing.Optional[bool] = None,
336    ):
337        """Makes the HTTP request (synchronous) and returns deserialized data.
338
339        To make an async_req request, set the async_req parameter.
340
341        :param resource_path: Path to method endpoint.
342        :param method: Method to call.
343        :param path_params: Path parameters in the url.
344        :param query_params: Query parameters in the url.
345        :param header_params: Header parameters to be
346            placed in the request header.
347        :param body: Request body.
348        :param post_params dict: Request post form parameters,
349            for `application/x-www-form-urlencoded`, `multipart/form-data`.
350        :param auth_settings list: Auth Settings names for the request.
351        :param response_type: For the response, a tuple containing:
352            valid classes
353            a list containing valid classes (for list schemas)
354            a dict containing a tuple of valid classes as the value
355            Example values:
356            (str,)
357            (Pet,)
358            (float, none_type)
359            ([int, none_type],)
360            ({str: (bool, str, int, float, date, datetime, str, none_type)},)
361        :param files: key -> field name, value -> a list of open file
362            objects for `multipart/form-data`.
363        :type files: dict
364        :param async_req bool: execute request asynchronously
365        :type async_req: bool, optional
366        :param _return_http_data_only: response data without head status code
367                                       and headers
368        :type _return_http_data_only: bool, optional
369        :param collection_formats: dict of collection formats for path, query,
370            header, and post parameters.
371        :type collection_formats: dict, optional
372        :param _preload_content: if False, the urllib3.HTTPResponse object will
373                                 be returned without reading/decoding response
374                                 data. Default is True.
375        :type _preload_content: bool, optional
376        :param _request_timeout: timeout setting for this request. If one
377                                 number provided, it will be total request
378                                 timeout. It can also be a pair (tuple) of
379                                 (connection, read) timeouts.
380        :param _check_type: boolean describing if the data back from the server
381            should have its type checked.
382        :type _check_type: bool, optional
383        :return:
384            If async_req parameter is True,
385            the request will be called asynchronously.
386            The method will return the request thread.
387            If parameter async_req is False or missing,
388            then the method will return the response directly.
389        """
390        if not async_req:
391            return self.__call_api(
392                resource_path,
393                method,
394                path_params,
395                query_params,
396                header_params,
397                body,
398                post_params,
399                files,
400                response_type,
401                auth_settings,
402                _return_http_data_only,
403                collection_formats,
404                _preload_content,
405                _request_timeout,
406                _host,
407                _check_type,
408            )
409
410        return self.pool.apply_async(
411            self.__call_api,
412            (
413                resource_path,
414                method,
415                path_params,
416                query_params,
417                header_params,
418                body,
419                post_params,
420                files,
421                response_type,
422                auth_settings,
423                _return_http_data_only,
424                collection_formats,
425                _preload_content,
426                _request_timeout,
427                _host,
428                _check_type,
429            ),
430        )

Makes the HTTP request (synchronous) and returns deserialized data.

To make an async_req request, set the async_req parameter.

Parameters
  • resource_path: Path to method endpoint.
  • method: Method to call.
  • path_params: Path parameters in the url.
  • query_params: Query parameters in the url.
  • header_params: Header parameters to be placed in the request header.
  • body: Request body.
  • post_params dict: Request post form parameters, for application/x-www-form-urlencoded, multipart/form-data.
  • auth_settings list: Auth Settings names for the request.
  • response_type: For the response, a tuple containing: valid classes a list containing valid classes (for list schemas) a dict containing a tuple of valid classes as the value Example values: (str,) (Pet,) (float, none_type) ([int, none_type],) ({str: (bool, str, int, float, date, datetime, str, none_type)},)
  • files: key -> field name, value -> a list of open file objects for multipart/form-data.
  • async_req bool: execute request asynchronously
  • _return_http_data_only: response data without head status code and headers
  • collection_formats: dict of collection formats for path, query, header, and post parameters.
  • _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True.
  • _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts.
  • _check_type: boolean describing if the data back from the server should have its type checked.
Returns
If async_req parameter is True,
the request will be called asynchronously.
The method will return the request thread.
If parameter async_req is False or missing,
then the method will return the response directly.
def request( self, method, url, query_params=None, headers=None, post_params=None, body=None, _preload_content=True, _request_timeout=None):
432    def request(
433        self,
434        method,
435        url,
436        query_params=None,
437        headers=None,
438        post_params=None,
439        body=None,
440        _preload_content=True,
441        _request_timeout=None,
442    ):
443        """Makes the HTTP request using RESTClient."""
444        if method == "GET":
445            return self.rest_client.GET(
446                url,
447                query_params=query_params,
448                _preload_content=_preload_content,
449                _request_timeout=_request_timeout,
450                headers=headers,
451            )
452        elif method == "HEAD":
453            return self.rest_client.HEAD(
454                url,
455                query_params=query_params,
456                _preload_content=_preload_content,
457                _request_timeout=_request_timeout,
458                headers=headers,
459            )
460        elif method == "OPTIONS":
461            return self.rest_client.OPTIONS(
462                url,
463                query_params=query_params,
464                headers=headers,
465                post_params=post_params,
466                _preload_content=_preload_content,
467                _request_timeout=_request_timeout,
468                body=body,
469            )
470        elif method == "POST":
471            return self.rest_client.POST(
472                url,
473                query_params=query_params,
474                headers=headers,
475                post_params=post_params,
476                _preload_content=_preload_content,
477                _request_timeout=_request_timeout,
478                body=body,
479            )
480        elif method == "PUT":
481            return self.rest_client.PUT(
482                url,
483                query_params=query_params,
484                headers=headers,
485                post_params=post_params,
486                _preload_content=_preload_content,
487                _request_timeout=_request_timeout,
488                body=body,
489            )
490        elif method == "PATCH":
491            return self.rest_client.PATCH(
492                url,
493                query_params=query_params,
494                headers=headers,
495                post_params=post_params,
496                _preload_content=_preload_content,
497                _request_timeout=_request_timeout,
498                body=body,
499            )
500        elif method == "DELETE":
501            return self.rest_client.DELETE(
502                url,
503                query_params=query_params,
504                headers=headers,
505                _preload_content=_preload_content,
506                _request_timeout=_request_timeout,
507                body=body,
508            )
509        else:
510            raise ApiValueError("http method must be `GET`, `HEAD`, `OPTIONS`," " `POST`, `PATCH`, `PUT` or `DELETE`.")

Makes the HTTP request using RESTClient.

def parameters_to_tuples(self, params, collection_formats):
512    def parameters_to_tuples(self, params, collection_formats):
513        """Get parameters as list of tuples, formatting collections.
514
515        :param params: Parameters as dict or list of two-tuples
516        :param dict collection_formats: Parameter collection formats
517        :return: Parameters as list of tuples, collections formatted
518        """
519        new_params = []
520        if collection_formats is None:
521            collection_formats = {}
522        for k, v in params.items() if isinstance(params, dict) else params:  # noqa: E501
523            if k in collection_formats:
524                collection_format = collection_formats[k]
525                if collection_format == "multi":
526                    new_params.extend((k, value) for value in v)
527                else:
528                    if collection_format == "ssv":
529                        delimiter = " "
530                    elif collection_format == "tsv":
531                        delimiter = "\t"
532                    elif collection_format == "pipes":
533                        delimiter = "|"
534                    else:  # csv is the default
535                        delimiter = ","
536                    new_params.append((k, delimiter.join(str(value) for value in v)))
537            else:
538                new_params.append((k, v))
539        return new_params

Get parameters as list of tuples, formatting collections.

Parameters
  • params: Parameters as dict or list of two-tuples
  • dict collection_formats: Parameter collection formats
Returns

Parameters as list of tuples, collections formatted

@staticmethod
def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes:
541    @staticmethod
542    def get_file_data_and_close_file(file_instance: io.IOBase) -> bytes:
543        file_data = file_instance.read()
544        file_instance.close()
545        return file_data
def files_parameters(self, files: Optional[Dict[str, List[io.IOBase]]] = None):
547    def files_parameters(self, files: typing.Optional[typing.Dict[str, typing.List[io.IOBase]]] = None):
548        """Builds form parameters.
549
550        :param files: None or a dict with key=param_name and
551            value is a list of open file objects
552        :return: List of tuples of form parameters with file data
553        """
554        if files is None:
555            return []
556
557        params = []
558        for param_name, file_instances in files.items():
559            if file_instances is None:
560                # if the file field is nullable, skip None values
561                continue
562            for file_instance in file_instances:
563                if file_instance is None:
564                    # if the file field is nullable, skip None values
565                    continue
566                if file_instance.closed is True:
567                    raise ApiValueError(
568                        "Cannot read a closed file. The passed in file_type " "for %s must be open." % param_name
569                    )
570                filename = os.path.basename(file_instance.name)
571                filedata = self.get_file_data_and_close_file(file_instance)
572                mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
573                params.append(tuple([param_name, tuple([filename, filedata, mimetype])]))
574
575        return params

Builds form parameters.

Parameters
  • files: None or a dict with key=param_name and value is a list of open file objects
Returns

List of tuples of form parameters with file data

def select_header_accept(self, accepts):
577    def select_header_accept(self, accepts):
578        """Returns `Accept` based on an array of accepts provided.
579
580        :param accepts: List of headers.
581        :return: Accept (e.g. application/json).
582        """
583        if not accepts:
584            return
585
586        accepts = [x.lower() for x in accepts]
587
588        if "application/json" in accepts:
589            return "application/json"
590        else:
591            return ", ".join(accepts)

Returns Accept based on an array of accepts provided.

Parameters
  • accepts: List of headers.
Returns

Accept (e.g. application/json).

def select_header_content_type(self, content_types):
593    def select_header_content_type(self, content_types):
594        """Returns `Content-Type` based on an array of content_types provided.
595
596        :param content_types: List of content-types.
597        :return: Content-Type (e.g. application/json).
598        """
599        if not content_types:
600            return "application/json"
601
602        content_types = [x.lower() for x in content_types]
603
604        if "application/json" in content_types or "*/*" in content_types:
605            return "application/json"
606        else:
607            return content_types[0]

Returns Content-Type based on an array of content_types provided.

Parameters
  • content_types: List of content-types.
Returns

Content-Type (e.g. application/json).

def update_params_for_auth(self, headers, querys, auth_settings, resource_path, method, body):
609    def update_params_for_auth(self, headers, querys, auth_settings, resource_path, method, body):
610        """Updates header and query params based on authentication setting.
611
612        :param headers: Header parameters dict to be updated.
613        :param querys: Query parameters tuple list to be updated.
614        :param auth_settings: Authentication setting identifiers list.
615        :param resource_path: A string representation of the HTTP request resource path.
616        :param method: A string representation of the HTTP request method.
617        :param body: A object representing the body of the HTTP request.
618            The object type is the return value of _encoder.default().
619        """
620        if not auth_settings:
621            return
622
623        for auth in auth_settings:
624            auth_setting = self.configuration.auth_settings().get(auth)
625            if auth_setting:
626                if auth_setting["in"] == "cookie":
627                    headers["Cookie"] = auth_setting["value"]
628                elif auth_setting["in"] == "header":
629                    if auth_setting["type"] != "http-signature":
630                        headers[auth_setting["key"]] = auth_setting["value"]
631                elif auth_setting["in"] == "query":
632                    querys.append((auth_setting["key"], auth_setting["value"]))
633                else:
634                    raise ApiValueError("Authentication token must be in `query` or `header`")

Updates header and query params based on authentication setting.

Parameters
  • headers: Header parameters dict to be updated.
  • querys: Query parameters tuple list to be updated.
  • auth_settings: Authentication setting identifiers list.
  • resource_path: A string representation of the HTTP request resource path.
  • method: A string representation of the HTTP request method.
  • body: A object representing the body of the HTTP request. The object type is the return value of _encoder.default().
class Endpoint:
637class Endpoint(object):
638    def __init__(self, settings=None, params_map=None, root_map=None, headers_map=None, api_client=None, callable=None):
639        """Creates an endpoint
640
641        Args:
642            settings (dict): see below key value pairs
643                'response_type' (tuple/None): response type
644                'auth' (list): a list of auth type keys
645                'endpoint_path' (str): the endpoint path
646                'operation_id' (str): endpoint string identifier
647                'http_method' (str): POST/PUT/PATCH/GET etc
648                'servers' (list): list of str servers that this endpoint is at
649            params_map (dict): see below key value pairs
650                'all' (list): list of str endpoint parameter names
651                'required' (list): list of required parameter names
652                'nullable' (list): list of nullable parameter names
653                'enum' (list): list of parameters with enum values
654                'validation' (list): list of parameters with validations
655            root_map
656                'validations' (dict): the dict mapping endpoint parameter tuple
657                    paths to their validation dictionaries
658                'allowed_values' (dict): the dict mapping endpoint parameter
659                    tuple paths to their allowed_values (enum) dictionaries
660                'openapi_types' (dict): param_name to openapi type
661                'attribute_map' (dict): param_name to camelCase name
662                'location_map' (dict): param_name to  'body', 'file', 'form',
663                    'header', 'path', 'query'
664                collection_format_map (dict): param_name to `csv` etc.
665            headers_map (dict): see below key value pairs
666                'accept' (list): list of Accept header strings
667                'content_type' (list): list of Content-Type header strings
668            api_client (ApiClient) api client instance
669            callable (function): the function which is invoked when the
670                Endpoint is called
671        """
672        self.settings = settings
673        self.params_map = params_map
674        self.params_map["all"].extend(
675            [
676                "async_req",
677                "_host_index",
678                "_preload_content",
679                "_request_timeout",
680                "_return_http_data_only",
681                "_check_input_type",
682                "_check_return_type",
683            ]
684        )
685        self.params_map["nullable"].extend(["_request_timeout"])
686        self.validations = root_map["validations"]
687        self.allowed_values = root_map["allowed_values"]
688        self.openapi_types = root_map["openapi_types"]
689        extra_types = {
690            "async_req": (bool,),
691            "_host_index": (none_type, int),
692            "_preload_content": (bool,),
693            "_request_timeout": (none_type, float, (float,), [float], int, (int,), [int]),
694            "_return_http_data_only": (bool,),
695            "_check_input_type": (bool,),
696            "_check_return_type": (bool,),
697        }
698        self.openapi_types.update(extra_types)
699        self.attribute_map = root_map["attribute_map"]
700        self.location_map = root_map["location_map"]
701        self.collection_format_map = root_map["collection_format_map"]
702        self.headers_map = headers_map
703        self.api_client = api_client
704        self.callable = callable
705
706    def __validate_inputs(self, kwargs):
707        for param in self.params_map["enum"]:
708            if param in kwargs:
709                check_allowed_values(self.allowed_values, (param,), kwargs[param])
710
711        for param in self.params_map["validation"]:
712            if param in kwargs:
713                check_validations(
714                    self.validations, (param,), kwargs[param], configuration=self.api_client.configuration
715                )
716
717        if kwargs["_check_input_type"] is False:
718            return
719
720        for key, value in kwargs.items():
721            fixed_val = validate_and_convert_types(
722                value,
723                self.openapi_types[key],
724                [key],
725                False,
726                kwargs["_check_input_type"],
727                configuration=self.api_client.configuration,
728            )
729            kwargs[key] = fixed_val
730
731    def __gather_params(self, kwargs):
732        params = {"body": None, "collection_format": {}, "file": {}, "form": [], "header": {}, "path": {}, "query": []}
733
734        for param_name, param_value in kwargs.items():
735            param_location = self.location_map.get(param_name)
736            if param_location is None:
737                continue
738            if param_location:
739                if param_location == "body":
740                    params["body"] = param_value
741                    continue
742                base_name = self.attribute_map[param_name]
743                if param_location == "form" and self.openapi_types[param_name] == (file_type,):
744                    params["file"][param_name] = [param_value]
745                elif param_location == "form" and self.openapi_types[param_name] == ([file_type],):
746                    # param_value is already a list
747                    params["file"][param_name] = param_value
748                elif param_location in {"form", "query"}:
749                    param_value_full = (base_name, param_value)
750                    params[param_location].append(param_value_full)
751                if param_location not in {"form", "query"}:
752                    params[param_location][base_name] = param_value
753                collection_format = self.collection_format_map.get(param_name)
754                if collection_format:
755                    params["collection_format"][base_name] = collection_format
756
757        return params
758
759    def __call__(self, *args, **kwargs):
760        """This method is invoked when endpoints are called
761        Example:
762
763        api_instance = IndexOperationsApi()
764        api_instance.configure_index  # this is an instance of the class Endpoint
765        api_instance.configure_index()  # this invokes api_instance.configure_index.__call__()
766        which then invokes the callable functions stored in that endpoint at
767        api_instance.configure_index.callable or self.callable in this class
768
769        """
770        return self.callable(self, *args, **kwargs)
771
772    def call_with_http_info(self, **kwargs):
773        try:
774            index = (
775                self.api_client.configuration.server_operation_index.get(
776                    self.settings["operation_id"], self.api_client.configuration.server_index
777                )
778                if kwargs["_host_index"] is None
779                else kwargs["_host_index"]
780            )
781            server_variables = self.api_client.configuration.server_operation_variables.get(
782                self.settings["operation_id"], self.api_client.configuration.server_variables
783            )
784            _host = self.api_client.configuration.get_host_from_settings(
785                index, variables=server_variables, servers=self.settings["servers"]
786            )
787        except IndexError:
788            if self.settings["servers"]:
789                raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(self.settings["servers"]))
790            _host = None
791
792        for key, value in kwargs.items():
793            if key not in self.params_map["all"]:
794                raise ApiTypeError(
795                    "Got an unexpected parameter '%s'" " to method `%s`" % (key, self.settings["operation_id"])
796                )
797            # only throw this nullable ApiValueError if _check_input_type
798            # is False, if _check_input_type==True we catch this case
799            # in self.__validate_inputs
800            if key not in self.params_map["nullable"] and value is None and kwargs["_check_input_type"] is False:
801                raise ApiValueError(
802                    "Value may not be None for non-nullable parameter `%s`"
803                    " when calling `%s`" % (key, self.settings["operation_id"])
804                )
805
806        for key in self.params_map["required"]:
807            if key not in kwargs.keys():
808                raise ApiValueError(
809                    "Missing the required parameter `%s` when calling " "`%s`" % (key, self.settings["operation_id"])
810                )
811
812        self.__validate_inputs(kwargs)
813
814        params = self.__gather_params(kwargs)
815
816        accept_headers_list = self.headers_map["accept"]
817        if accept_headers_list:
818            params["header"]["Accept"] = self.api_client.select_header_accept(accept_headers_list)
819
820        content_type_headers_list = self.headers_map["content_type"]
821        if content_type_headers_list:
822            header_list = self.api_client.select_header_content_type(content_type_headers_list)
823            params["header"]["Content-Type"] = header_list
824
825        return self.api_client.call_api(
826            self.settings["endpoint_path"],
827            self.settings["http_method"],
828            params["path"],
829            params["query"],
830            params["header"],
831            body=params["body"],
832            post_params=params["form"],
833            files=params["file"],
834            response_type=self.settings["response_type"],
835            auth_settings=self.settings["auth"],
836            async_req=kwargs["async_req"],
837            _check_type=kwargs["_check_return_type"],
838            _return_http_data_only=kwargs["_return_http_data_only"],
839            _preload_content=kwargs["_preload_content"],
840            _request_timeout=kwargs["_request_timeout"],
841            _host=_host,
842            collection_formats=params["collection_format"],
843        )
Endpoint( settings=None, params_map=None, root_map=None, headers_map=None, api_client=None, callable=None)
638    def __init__(self, settings=None, params_map=None, root_map=None, headers_map=None, api_client=None, callable=None):
639        """Creates an endpoint
640
641        Args:
642            settings (dict): see below key value pairs
643                'response_type' (tuple/None): response type
644                'auth' (list): a list of auth type keys
645                'endpoint_path' (str): the endpoint path
646                'operation_id' (str): endpoint string identifier
647                'http_method' (str): POST/PUT/PATCH/GET etc
648                'servers' (list): list of str servers that this endpoint is at
649            params_map (dict): see below key value pairs
650                'all' (list): list of str endpoint parameter names
651                'required' (list): list of required parameter names
652                'nullable' (list): list of nullable parameter names
653                'enum' (list): list of parameters with enum values
654                'validation' (list): list of parameters with validations
655            root_map
656                'validations' (dict): the dict mapping endpoint parameter tuple
657                    paths to their validation dictionaries
658                'allowed_values' (dict): the dict mapping endpoint parameter
659                    tuple paths to their allowed_values (enum) dictionaries
660                'openapi_types' (dict): param_name to openapi type
661                'attribute_map' (dict): param_name to camelCase name
662                'location_map' (dict): param_name to  'body', 'file', 'form',
663                    'header', 'path', 'query'
664                collection_format_map (dict): param_name to `csv` etc.
665            headers_map (dict): see below key value pairs
666                'accept' (list): list of Accept header strings
667                'content_type' (list): list of Content-Type header strings
668            api_client (ApiClient) api client instance
669            callable (function): the function which is invoked when the
670                Endpoint is called
671        """
672        self.settings = settings
673        self.params_map = params_map
674        self.params_map["all"].extend(
675            [
676                "async_req",
677                "_host_index",
678                "_preload_content",
679                "_request_timeout",
680                "_return_http_data_only",
681                "_check_input_type",
682                "_check_return_type",
683            ]
684        )
685        self.params_map["nullable"].extend(["_request_timeout"])
686        self.validations = root_map["validations"]
687        self.allowed_values = root_map["allowed_values"]
688        self.openapi_types = root_map["openapi_types"]
689        extra_types = {
690            "async_req": (bool,),
691            "_host_index": (none_type, int),
692            "_preload_content": (bool,),
693            "_request_timeout": (none_type, float, (float,), [float], int, (int,), [int]),
694            "_return_http_data_only": (bool,),
695            "_check_input_type": (bool,),
696            "_check_return_type": (bool,),
697        }
698        self.openapi_types.update(extra_types)
699        self.attribute_map = root_map["attribute_map"]
700        self.location_map = root_map["location_map"]
701        self.collection_format_map = root_map["collection_format_map"]
702        self.headers_map = headers_map
703        self.api_client = api_client
704        self.callable = callable

Creates an endpoint

Arguments:
  • settings (dict): see below key value pairs 'response_type' (tuple/None): response type 'auth' (list): a list of auth type keys 'endpoint_path' (str): the endpoint path 'operation_id' (str): endpoint string identifier 'http_method' (str): POST/PUT/PATCH/GET etc 'servers' (list): list of str servers that this endpoint is at
  • params_map (dict): see below key value pairs 'all' (list): list of str endpoint parameter names 'required' (list): list of required parameter names 'nullable' (list): list of nullable parameter names 'enum' (list): list of parameters with enum values 'validation' (list): list of parameters with validations
  • root_map 'validations' (dict): the dict mapping endpoint parameter tuple paths to their validation dictionaries 'allowed_values' (dict): the dict mapping endpoint parameter tuple paths to their allowed_values (enum) dictionaries 'openapi_types' (dict): param_name to openapi type 'attribute_map' (dict): param_name to camelCase name 'location_map' (dict): param_name to 'body', 'file', 'form', 'header', 'path', 'query' collection_format_map (dict): param_name to csv etc.
  • headers_map (dict): see below key value pairs 'accept' (list): list of Accept header strings 'content_type' (list): list of Content-Type header strings
  • api_client (ApiClient) api client instance
  • callable (function): the function which is invoked when the Endpoint is called
settings
params_map
validations
allowed_values
openapi_types
attribute_map
location_map
collection_format_map
headers_map
api_client
callable
def call_with_http_info(self, **kwargs):
772    def call_with_http_info(self, **kwargs):
773        try:
774            index = (
775                self.api_client.configuration.server_operation_index.get(
776                    self.settings["operation_id"], self.api_client.configuration.server_index
777                )
778                if kwargs["_host_index"] is None
779                else kwargs["_host_index"]
780            )
781            server_variables = self.api_client.configuration.server_operation_variables.get(
782                self.settings["operation_id"], self.api_client.configuration.server_variables
783            )
784            _host = self.api_client.configuration.get_host_from_settings(
785                index, variables=server_variables, servers=self.settings["servers"]
786            )
787        except IndexError:
788            if self.settings["servers"]:
789                raise ApiValueError("Invalid host index. Must be 0 <= index < %s" % len(self.settings["servers"]))
790            _host = None
791
792        for key, value in kwargs.items():
793            if key not in self.params_map["all"]:
794                raise ApiTypeError(
795                    "Got an unexpected parameter '%s'" " to method `%s`" % (key, self.settings["operation_id"])
796                )
797            # only throw this nullable ApiValueError if _check_input_type
798            # is False, if _check_input_type==True we catch this case
799            # in self.__validate_inputs
800            if key not in self.params_map["nullable"] and value is None and kwargs["_check_input_type"] is False:
801                raise ApiValueError(
802                    "Value may not be None for non-nullable parameter `%s`"
803                    " when calling `%s`" % (key, self.settings["operation_id"])
804                )
805
806        for key in self.params_map["required"]:
807            if key not in kwargs.keys():
808                raise ApiValueError(
809                    "Missing the required parameter `%s` when calling " "`%s`" % (key, self.settings["operation_id"])
810                )
811
812        self.__validate_inputs(kwargs)
813
814        params = self.__gather_params(kwargs)
815
816        accept_headers_list = self.headers_map["accept"]
817        if accept_headers_list:
818            params["header"]["Accept"] = self.api_client.select_header_accept(accept_headers_list)
819
820        content_type_headers_list = self.headers_map["content_type"]
821        if content_type_headers_list:
822            header_list = self.api_client.select_header_content_type(content_type_headers_list)
823            params["header"]["Content-Type"] = header_list
824
825        return self.api_client.call_api(
826            self.settings["endpoint_path"],
827            self.settings["http_method"],
828            params["path"],
829            params["query"],
830            params["header"],
831            body=params["body"],
832            post_params=params["form"],
833            files=params["file"],
834            response_type=self.settings["response_type"],
835            auth_settings=self.settings["auth"],
836            async_req=kwargs["async_req"],
837            _check_type=kwargs["_check_return_type"],
838            _return_http_data_only=kwargs["_return_http_data_only"],
839            _preload_content=kwargs["_preload_content"],
840            _request_timeout=kwargs["_request_timeout"],
841            _host=_host,
842            collection_formats=params["collection_format"],
843        )