@@ -6,24 +6,25 @@ import mimetypes
6
6
import warnings
7
7
import multiprocessing
8
8
from multiprocessing.pool import ThreadPool
9
+ from datetime import date, datetime
9
10
import io
10
11
import os
11
12
import re
12
13
from typing import Any, Dict, Optional, List, Tuple, Union
14
+ from typing_extensions import Self
13
15
from urllib.parse import quote
14
16
from urllib3.fields import RequestField # type: ignore
15
17
16
18
17
19
from {{ package }} import rest
20
+ from {{ package }}.configuration import Configuration
18
21
from {{ package }}.exceptions import ApiTypeError, ApiValueError
19
22
from {{ package }}.model_utils import (
20
23
ModelNormal,
21
24
ModelSimple,
22
25
ModelComposed,
23
26
check_allowed_values,
24
27
check_validations,
25
- date,
26
- datetime,
27
28
deserialize_file,
28
29
file_type,
29
30
model_to_dict,
@@ -32,7 +33,7 @@ from {{ package }}.model_utils import (
32
33
)
33
34
34
35
35
- class ApiClient(object) :
36
+ class ApiClient:
36
37
"""Generic API client for OpenAPI client library builds.
37
38
38
39
OpenAPI generic API client. This client handles the client-
@@ -46,7 +47,7 @@ class ApiClient(object):
46
47
the API.
47
48
"""
48
49
49
- def __init__(self, configuration):
50
+ def __init__(self, configuration: Configuration ):
50
51
self.configuration = configuration
51
52
52
53
self.rest_client = self._build_rest_client()
@@ -56,28 +57,28 @@ class ApiClient(object):
56
57
# Set default User-Agent.
57
58
self.user_agent = user_agent()
58
59
59
- def __enter__(self):
60
+ def __enter__(self) -> Self :
60
61
return self
61
62
62
- def __exit__(self, exc_type, exc_value, traceback):
63
+ def __exit__(self, exc_type, exc_value, traceback) -> None :
63
64
self.close()
64
65
65
- def close(self):
66
+ def close(self) -> None :
66
67
self.rest_client.pool_manager.clear()
67
68
68
69
def _build_rest_client(self):
69
70
return rest.RESTClientObject(self.configuration)
70
71
71
72
@property
72
- def user_agent(self):
73
+ def user_agent(self) -> str :
73
74
"""User agent for this API client"""
74
75
return self.default_headers["User-Agent"]
75
76
76
77
@user_agent.setter
77
- def user_agent(self, value) :
78
+ def user_agent(self, value: str) -> None :
78
79
self.default_headers["User-Agent"] = value
79
80
80
- def set_default_header(self, header_name, header_value) :
81
+ def set_default_header(self, header_name: str , header_value: str) -> None :
81
82
self.default_headers[header_name] = header_value
82
83
83
84
def _call_api(
@@ -91,7 +92,7 @@ class ApiClient(object):
91
92
response_type: Optional[Tuple[Any]] = None,
92
93
return_http_data_only: Optional[bool] = None,
93
94
preload_content: bool = True,
94
- request_timeout: Optional[Union[int, float, Tuple]] = None,
95
+ request_timeout: Optional[Union[int, float, Tuple[Union[int, float], Union[int, float]] ]] = None,
95
96
check_type: Optional[bool] = None,
96
97
):
97
98
# perform request and return response
@@ -133,19 +134,16 @@ class ApiClient(object):
133
134
return return_data
134
135
return (return_data, response.status, response.getheaders())
135
136
136
- def parameters_to_multipart(self, params, collection_types ):
137
- """Get parameters as list of tuples, formatting as json if value is collection_types .
137
+ def parameters_to_multipart(self, params):
138
+ """Get parameters as list of tuples, formatting as json if value is dict .
138
139
139
140
:param params: Parameters as list of two-tuples.
140
- :param collection_types: Parameter collection types.
141
141
142
142
:return: Parameters as list of tuple or urllib3.fields.RequestField
143
143
"""
144
144
new_params = []
145
- if collection_types is None:
146
- collection_types = dict
147
145
for k, v in params.items() if isinstance(params, dict) else params:
148
- if isinstance(v, collection_types ): # v is instance of collection_type, formatting as application/json
146
+ if isinstance(v, dict ): # v is instance of collection_type, formatting as application/json
149
147
v = json.dumps(v, ensure_ascii=False).encode("utf-8")
150
148
field = RequestField(k, v)
151
149
field.make_multipart(content_type="application/json; charset=utf-8")
@@ -175,7 +173,7 @@ class ApiClient(object):
175
173
elif isinstance(obj, (str, int, float, bool)) or obj is None:
176
174
return obj
177
175
elif isinstance(obj, (datetime, date)):
178
- if obj. tzinfo is not None:
176
+ if getattr( obj, " tzinfo", None) is not None:
179
177
return obj.isoformat()
180
178
return obj.strftime("%Y-%m-%dT%H:%M:%S") + obj.strftime(".%f")[:4] + "Z"
181
179
elif isinstance(obj, ModelSimple):
@@ -186,7 +184,7 @@ class ApiClient(object):
186
184
return {key: cls.sanitize_for_serialization(val) for key, val in obj.items()}
187
185
raise ApiValueError("Unable to prepare type {} for serialization".format(obj.__class__.__name__))
188
186
189
- def deserialize(self, response_data, response_type, check_type):
187
+ def deserialize(self, response_data: str , response_type: Any , check_type: Optional[bool] ):
190
188
"""Deserializes response into an object.
191
189
192
190
:param response_data: Response data to be deserialized.
@@ -233,7 +231,7 @@ class ApiClient(object):
233
231
return_http_data_only: Optional[bool] = None,
234
232
collection_formats: Optional[Dict[str, str]] = None,
235
233
preload_content: bool = True,
236
- request_timeout: Optional[Union[int, float, Tuple]] = None,
234
+ request_timeout: Optional[Union[int, float, Tuple[Union[int, float], Union[int, float]] ]] = None,
237
235
host: Optional[str] = None,
238
236
check_type: Optional[bool] = None,
239
237
):
@@ -310,7 +308,7 @@ class ApiClient(object):
310
308
post_params = self.parameters_to_tuples(post_params, collection_formats)
311
309
post_params.extend(self.files_parameters(files))
312
310
if header_params["Content-Type"].startswith("multipart"):
313
- post_params = self.parameters_to_multipart(post_params, (dict) )
311
+ post_params = self.parameters_to_multipart(post_params)
314
312
315
313
# body
316
314
if body:
@@ -404,15 +402,15 @@ class ApiClient(object):
404
402
405
403
return params
406
404
407
- def select_header_accept(self, accepts) :
405
+ def select_header_accept(self, accepts: List[str]) -> str :
408
406
"""Returns `Accept` based on an array of accepts provided.
409
407
410
408
:param accepts: List of headers.
411
409
:return: Accept (e.g. application/json).
412
410
"""
413
411
return ", ".join(accepts)
414
412
415
- def select_header_content_type(self, content_types) :
413
+ def select_header_content_type(self, content_types: List[str]) -> str :
416
414
"""Returns `Content-Type` based on an array of content_types provided.
417
415
418
416
:param content_types: List of content-types.
@@ -432,15 +430,15 @@ class ThreadedApiClient(ApiClient):
432
430
433
431
_pool = None
434
432
435
- def __init__(self, configuration, pool_threads= 1):
433
+ def __init__(self, configuration: Configuration , pool_threads: int = 1):
436
434
self.pool_threads = pool_threads
437
435
self.connection_pool_maxsize = multiprocessing.cpu_count() * 5
438
436
super().__init__(configuration)
439
437
440
438
def _build_rest_client(self):
441
439
return rest.RESTClientObject(self.configuration, maxsize=self.connection_pool_maxsize)
442
440
443
- def close(self):
441
+ def close(self) -> None :
444
442
self.rest_client.pool_manager.clear()
445
443
if self._pool:
446
444
self._pool.close()
@@ -450,7 +448,7 @@ class ThreadedApiClient(ApiClient):
450
448
atexit.unregister(self.close)
451
449
452
450
@property
453
- def pool(self):
451
+ def pool(self) -> ThreadPool :
454
452
"""Create thread pool on first request
455
453
avoids instantiating unused threadpool for blocking clients.
456
454
"""
@@ -487,15 +485,15 @@ class ThreadedApiClient(ApiClient):
487
485
preload_content,
488
486
request_timeout,
489
487
check_type,
490
- )
488
+ ),
491
489
)
492
490
493
491
494
492
class AsyncApiClient(ApiClient):
495
493
def _build_rest_client(self):
496
494
return rest.AsyncRESTClientObject(self.configuration)
497
495
498
- async def __aenter__(self):
496
+ async def __aenter__(self) -> Self :
499
497
return self
500
498
501
499
async def __aexit__(self, _exc_type, exc, _tb):
@@ -514,7 +512,7 @@ class AsyncApiClient(ApiClient):
514
512
response_type: Optional[Tuple[Any]] = None,
515
513
return_http_data_only: Optional[bool] = None,
516
514
preload_content: bool = True,
517
- request_timeout: Optional[Union[int, float, Tuple]] = None,
515
+ request_timeout: Optional[Union[int, float, Tuple[Union[int, float], Union[int, float]] ]] = None,
518
516
check_type: Optional[bool] = None,
519
517
):
520
518
@@ -553,8 +551,14 @@ class AsyncApiClient(ApiClient):
553
551
return (return_data, response.status_code, response.headers)
554
552
555
553
556
- class Endpoint(object):
557
- def __init__(self, settings=None, params_map=None, headers_map=None, api_client=None):
554
+ class Endpoint:
555
+ def __init__(
556
+ self,
557
+ settings: Dict[str, Any],
558
+ params_map: Dict[str, Dict[str, Any]],
559
+ headers_map: Dict[str, List[str]],
560
+ api_client: ApiClient,
561
+ ):
558
562
"""Creates an endpoint.
559
563
560
564
:param settings: See below key value pairs:
@@ -646,17 +650,16 @@ class Endpoint(object):
646
650
def call_with_http_info(self, **kwargs):
647
651
648
652
is_unstable = self.api_client.configuration.unstable_operations.get(
649
- "{}.{}".format(self.settings["version"], self.settings["operation_id"]))
653
+ "{}.{}".format(self.settings["version"], self.settings["operation_id"])
654
+ )
650
655
if is_unstable:
651
656
warnings.warn("Using unstable operation '{0}'".format(self.settings["operation_id"]))
652
657
elif is_unstable is False:
653
658
raise ApiValueError("Unstable operation '{0}' is disabled".format(self.settings["operation_id"]))
654
659
655
660
try:
656
- index = (
657
- self.api_client.configuration.server_operation_index.get(
658
- self.settings["operation_id"], self.api_client.configuration.server_index
659
- )
661
+ index = self.api_client.configuration.server_operation_index.get(
662
+ self.settings["operation_id"], self.api_client.configuration.server_index
660
663
)
661
664
server_variables = self.api_client.configuration.server_operation_variables.get(
662
665
self.settings["operation_id"], self.api_client.configuration.server_variables
@@ -677,7 +680,11 @@ class Endpoint(object):
677
680
# only throw this nullable ApiValueError if check_input_type
678
681
# is False, if check_input_type==True we catch this case
679
682
# in self._validate_inputs
680
- if not self.params_map[key].get("nullable") and value is None and not self.api_client.configuration.check_input_type:
683
+ if (
684
+ not self.params_map[key].get("nullable")
685
+ and value is None
686
+ and not self.api_client.configuration.check_input_type
687
+ ):
681
688
raise ApiValueError(
682
689
"Value may not be None for non-nullable parameter `%s`"
683
690
" when calling `%s`" % (key, self.settings["operation_id"])
@@ -722,7 +729,7 @@ class Endpoint(object):
722
729
collection_formats=params["collection_format"],
723
730
)
724
731
725
- def update_params_for_auth(self, headers, queries):
732
+ def update_params_for_auth(self, headers, queries) -> None :
726
733
"""Updates header and query params based on authentication setting.
727
734
728
735
:param headers: Header parameters dict to be updated.
@@ -745,7 +752,7 @@ class Endpoint(object):
745
752
raise ApiValueError("Authentication token must be in `query` or `header`")
746
753
747
754
748
- def user_agent():
755
+ def user_agent() -> str :
749
756
"""Generate default User-Agent header."""
750
757
import platform
751
758
from {{ package }}.version import __version__
0 commit comments