Skip to content
This repository was archived by the owner on Dec 25, 2024. It is now read-only.

Commit 87da2d7

Browse files
committed
Reduces generated code (#166)
* Converts PrefixSeparatorIterator, Api, and Encoding into dataclasses * ApiClient converted to dataclass * Removes __call_api * Removes unneeded type imports from header * Removes unneeded imports from headers * Removes unneeded imports in responses when they have no content or headers * Removes unneeded header imports * Removes pyi files * Removes functools import * Stops generating new for anytype schemas * Samples regenerated * Fixes this_package security tests
1 parent c89a639 commit 87da2d7

1,154 files changed

Lines changed: 612 additions & 5781 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

modules/openapi-json-schema-generator/src/main/resources/python/_helper_imports_schema_types.hbs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import datetime # noqa: F401
22
import decimal # noqa: F401
3-
import functools # noqa: F401
43
import io # noqa: F401
54
import re # noqa: F401
65
import typing # noqa: F401

modules/openapi-json-schema-generator/src/main/resources/python/api_client.hbs

Lines changed: 65 additions & 156 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import tornado.gen
2525
import frozendict
2626

2727
from {{packageName}} import exceptions, rest, schemas, security_schemes
28-
from {{packageName}}.configurations import schema_configuration, api_configuration
28+
from {{packageName}}.configurations import api_configuration, schema_configuration as schema_configuration_
2929

3030

3131
class RequestField(fields.RequestField):
@@ -77,18 +77,16 @@ class ParameterStyle(enum.Enum):
7777
DEEP_OBJECT = 'deepObject'
7878

7979

80+
@dataclasses.dataclass
8081
class PrefixSeparatorIterator:
8182
# A class to store prefixes and separators for rfc6570 expansions
83+
prefix: str
84+
separator: str
85+
first: bool = True
86+
item_separator: str = dataclasses.field(init=False)
8287

83-
def __init__(self, prefix: str, separator: str):
84-
self.prefix = prefix
85-
self.separator = separator
86-
self.first = True
87-
if separator in {'.', '|', '%20'}:
88-
item_separator = separator
89-
else:
90-
item_separator = ','
91-
self.item_separator = item_separator
88+
def __post_init__(self):
89+
self.item_separator = self.separator if self.separator in {'.', '|', '%20'} else ','
9290

9391
def __iter__(self):
9492
return self
@@ -331,20 +329,13 @@ class JSONDetector:
331329
return False
332330

333331

332+
@dataclasses.dataclass
334333
class Encoding:
335-
def __init__(
336-
self,
337-
content_type: str,
338-
headers: typing.Optional[typing.Dict[str, 'HeaderParameter']] = None,
339-
style: typing.Optional[ParameterStyle] = None,
340-
explode: bool = False,
341-
allow_reserved: bool = False,
342-
):
343-
self.content_type = content_type
344-
self.headers = headers
345-
self.style = style
346-
self.explode = explode
347-
self.allow_reserved = allow_reserved
334+
content_type: str
335+
headers: typing.Optional[typing.Dict[str, 'HeaderParameter']] = None
336+
style: typing.Optional[ParameterStyle] = None
337+
explode: bool = False
338+
allow_reserved: bool = False
348339

349340

350341
@dataclasses.dataclass
@@ -730,19 +721,6 @@ class ApiResponse:
730721
body: typing.Union[schemas.Unset, schemas.Schema] = schemas.unset
731722
headers: typing.Union[schemas.Unset, typing.Dict[str, schemas.Schema]] = schemas.unset
732723

733-
def __init__(
734-
self,
735-
response: urllib3.HTTPResponse,
736-
body: typing.Union[schemas.Unset, schemas.Schema] = schemas.unset,
737-
headers: typing.Union[schemas.Unset, typing.Dict[str, schemas.Schema]] = schemas.unset
738-
):
739-
"""
740-
pycharm needs this to prevent 'Unexpected argument' warnings
741-
"""
742-
self.response = response
743-
self.body = body
744-
self.headers = headers
745-
746724

747725
@dataclasses.dataclass
748726
class ApiResponseWithoutDeserialization(ApiResponse):
@@ -883,7 +861,7 @@ class OpenApiResponse(JSONDetector, TypedDictInputVerifier, typing.Generic[T]):
883861
}
884862

885863
@classmethod
886-
def deserialize(cls, response: urllib3.HTTPResponse, configuration: schema_configuration.SchemaConfiguration) -> T:
864+
def deserialize(cls, response: urllib3.HTTPResponse, configuration: schema_configuration_.SchemaConfiguration) -> T:
887865
content_type = response.headers.get('content-type')
888866
deserialized_body = schemas.unset
889867
streamed = response.supports_chunked_reads()
@@ -935,6 +913,7 @@ class OpenApiResponse(JSONDetector, TypedDictInputVerifier, typing.Generic[T]):
935913
)
936914

937915

916+
@dataclasses.dataclass
938917
class ApiClient:
939918
"""Generic API client for OpenAPI client library builds.
940919

@@ -948,37 +927,25 @@ class ApiClient:
948927
Do not edit the class manually.
949928

950929
:param configuration: api_configuration.ApiConfiguration object for this client
951-
:param schema_configuration: schema_configuration.SchemaConfiguration object for this client
952-
:param header_name: a header to pass when making calls to the API.
953-
:param header_value: a header value to pass when making calls to
954-
the API.
955-
:param cookie: a cookie to include in the header when making calls
956-
to the API
930+
:param schema_configuration: schema_configuration_.SchemaConfiguration object for this client
931+
:param default_headers: any default headers to include when making calls to the API.
957932
:param pool_threads: The number of threads to use for async requests
958933
to the API. More threads means more concurrent API requests.
959934
"""
960-
961-
_pool = None
962-
963-
def __init__(
964-
self,
965-
configuration: typing.Optional[api_configuration.ApiConfiguration] = None,
966-
schema_config: typing.Optional[schema_configuration.SchemaConfiguration] = None,
967-
header_name: typing.Optional[str] = None,
968-
header_value: typing.Optional[str] = None,
969-
cookie: typing.Optional[str] = None,
970-
pool_threads: int = 1
971-
):
972-
self.configuration: api_configuration.ApiConfiguration = configuration or api_configuration.ApiConfiguration()
973-
self.schema_configuration: schema_configuration.SchemaConfiguration = schema_config or schema_configuration.SchemaConfiguration()
974-
self.pool_threads = pool_threads
975-
self.rest_client = rest.RESTClientObject(self.configuration)
976-
self.default_headers = _collections.HTTPHeaderDict()
977-
if header_name is not None:
978-
self.default_headers[header_name] = header_value
979-
self.cookie = cookie
980-
# Set default User-Agent.
935+
configuration: api_configuration.ApiConfiguration = dataclasses.field(
936+
default_factory=lambda: api_configuration.ApiConfiguration())
937+
schema_configuration: schema_configuration_.SchemaConfiguration = dataclasses.field(
938+
default_factory=lambda: schema_configuration_.SchemaConfiguration())
939+
default_headers: _collections.HTTPHeaderDict = dataclasses.field(
940+
default_factory=lambda: _collections.HTTPHeaderDict())
941+
pool_threads: int = 1
942+
user_agent: str = dataclasses.field(init=False)
943+
rest_client: rest.RESTClientObject = dataclasses.field(init=False)
944+
945+
def __post_init__(self):
946+
self._pool = None
981947
self.user_agent = '{{#if httpUserAgent}}{{{httpUserAgent}}}{{/if}}{{#unless httpUserAgent}}OpenAPI-JSON-Schema-Generator/{{{packageVersion}}}/python{{/unless}}'
948+
self.rest_client = rest.RESTClientObject(self.configuration)
982949

983950
def __enter__(self):
984951
return self
@@ -1016,26 +983,46 @@ class ApiClient:
1016983
def set_default_header(self, header_name, header_value):
1017984
self.default_headers[header_name] = header_value
1018985

1019-
{{#if tornado}}
1020-
@tornado.gen.coroutine
1021-
{{/if}}
1022-
{{#if asyncio}}async {{/if}}def __call_api(
986+
def call_api(
1023987
self,
1024988
resource_path: str,
1025989
method: str,
1026990
host: str,
1027991
headers: typing.Optional[_collections.HTTPHeaderDict] = None,
1028-
body: typing.Optional[typing.Union[str, bytes]] = None,
992+
body: typing.Union[str, bytes, None] = None,
1029993
fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None,
1030994
security_requirement_object: typing.Optional[security_schemes.SecurityRequirementObject] = None,
1031995
stream: bool = False,
1032-
timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None,
996+
timeout: typing.Union[int, typing.Tuple, None] = None,
1033997
) -> urllib3.HTTPResponse:
998+
"""Makes the HTTP request (synchronous) and returns deserialized data.
1034999

1000+
:param resource_path: Path to method endpoint.
1001+
:param method: Method to call.
1002+
:param headers: Header parameters to be
1003+
placed in the request header.
1004+
:param body: Request body.
1005+
:param fields: Request post form parameters,
1006+
for `application/x-www-form-urlencoded`, `multipart/form-data`
1007+
:param security_requirement_object: The security requirement object, used to apply auth when making the call
1008+
:param async_req: execute request asynchronously
1009+
:param stream: if True, the urllib3.HTTPResponse object will
1010+
be returned without reading/decoding response
1011+
data. Also when True, if the openapi spec describes a file download,
1012+
the data will be written to a local filesystem file and the schemas.BinarySchema
1013+
instance will also inherit from FileSchema and schemas.FileIO
1014+
Default is False.
1015+
:type stream: bool, optional
1016+
:param timeout: timeout setting for this request. If one
1017+
number provided, it will be total request
1018+
timeout. It can also be a pair (tuple) of
1019+
(connection, read) timeouts.
1020+
:param host: api endpoint host
1021+
:return:
1022+
the method will return the response directly.
1023+
"""
10351024
# header parameters
10361025
used_headers = _collections.HTTPHeaderDict(self.default_headers)
1037-
if self.cookie:
1038-
headers['Cookie'] = self.cookie
10391026

10401027
# auth setting
10411028
self.update_params_for_auth(
@@ -1046,7 +1033,7 @@ class ApiClient:
10461033
body
10471034
)
10481035

1049-
# must happen after cookie setting and auth setting in case user is overriding those
1036+
# must happen after auth setting in case user is overriding those
10501037
if headers:
10511038
used_headers.update(headers)
10521039

@@ -1065,91 +1052,15 @@ class ApiClient:
10651052
)
10661053
return response
10671054

1068-
def call_api(
1069-
self,
1070-
resource_path: str,
1071-
method: str,
1072-
host: str,
1073-
headers: typing.Optional[_collections.HTTPHeaderDict] = None,
1074-
body: typing.Optional[typing.Union[str, bytes]] = None,
1075-
fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None,
1076-
security_requirement_object: typing.Optional[security_schemes.SecurityRequirementObject] = None,
1077-
async_req: typing.Optional[bool] = None,
1078-
stream: bool = False,
1079-
timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None,
1080-
) -> urllib3.HTTPResponse:
1081-
"""Makes the HTTP request (synchronous) and returns deserialized data.
1082-
1083-
To make an async_req request, set the async_req parameter.
1084-
1085-
:param resource_path: Path to method endpoint.
1086-
:param method: Method to call.
1087-
:param headers: Header parameters to be
1088-
placed in the request header.
1089-
:param body: Request body.
1090-
:param fields: Request post form parameters,
1091-
for `application/x-www-form-urlencoded`, `multipart/form-data`
1092-
:param security_requirement_object: The security requirement object, used to apply auth when making the call
1093-
:param async_req: execute request asynchronously
1094-
:type async_req: bool, optional TODO remove, unused
1095-
:param stream: if True, the urllib3.HTTPResponse object will
1096-
be returned without reading/decoding response
1097-
data. Also when True, if the openapi spec describes a file download,
1098-
the data will be written to a local filesystem file and the schemas.BinarySchema
1099-
instance will also inherit from FileSchema and schemas.FileIO
1100-
Default is False.
1101-
:type stream: bool, optional
1102-
:param timeout: timeout setting for this request. If one
1103-
number provided, it will be total request
1104-
timeout. It can also be a pair (tuple) of
1105-
(connection, read) timeouts.
1106-
:param host: api endpoint host
1107-
:return:
1108-
If async_req parameter is True,
1109-
the request will be called asynchronously.
1110-
The method will return the request thread.
1111-
If parameter async_req is False or missing,
1112-
then the method will return the response directly.
1113-
"""
1114-
1115-
if not async_req:
1116-
return self.__call_api(
1117-
resource_path,
1118-
method,
1119-
host,
1120-
headers,
1121-
body,
1122-
fields,
1123-
security_requirement_object,
1124-
stream,
1125-
timeout,
1126-
)
1127-
1128-
return self.pool.apply_async(
1129-
self.__call_api,
1130-
(
1131-
resource_path,
1132-
method,
1133-
host,
1134-
headers,
1135-
body,
1136-
json,
1137-
fields,
1138-
security_requirement_object,
1139-
stream,
1140-
timeout,
1141-
)
1142-
)
1143-
11441055
def request(
11451056
self,
11461057
method: str,
11471058
url: str,
11481059
headers: typing.Optional[_collections.HTTPHeaderDict] = None,
11491060
fields: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None,
1150-
body: typing.Optional[typing.Union[str, bytes]] = None,
1061+
body: typing.Union[str, bytes, None] = None,
11511062
stream: bool = False,
1152-
timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None,
1063+
timeout: typing.Union[int, typing.Tuple, None] = None,
11531064
) -> urllib3.HTTPResponse:
11541065
"""Makes the HTTP request using RESTClient."""
11551066
if method == "get":
@@ -1208,7 +1119,7 @@ class ApiClient:
12081119
security_requirement_object: typing.Optional[security_schemes.SecurityRequirementObject],
12091120
resource_path: str,
12101121
method: str,
1211-
body: typing.Optional[typing.Union[str, bytes]] = None
1122+
body: typing.Union[str, bytes, None] = None
12121123
):
12131124
"""Updates header and query params based on authentication setting.
12141125

@@ -1232,16 +1143,14 @@ class ApiClient:
12321143
scope_names
12331144
)
12341145

1235-
1146+
@dataclasses.dataclass
12361147
class Api(TypedDictInputVerifier):
12371148
"""NOTE: This class is auto generated by OpenAPI JSON Schema Generator
12381149
Ref: https://github.com/openapi-json-schema-tools/openapi-json-schema-generator
12391150

12401151
Do not edit the class manually.
12411152
"""
1242-
1243-
def __init__(self, api_client: typing.Optional[ApiClient] = None):
1244-
self.api_client: ApiClient = api_client or ApiClient()
1153+
api_client: ApiClient = dataclasses.field(default_factory=lambda: ApiClient())
12451154

12461155

12471156
class SerializedRequestBody(typing_extensions.TypedDict, total=False):

modules/openapi-json-schema-generator/src/main/resources/python/components/headers/header.hbs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@
1010
{{> _helper_imports }}
1111
{{jsonPathPiece.camelCase}} = {{refInfo.refModule}}.{{refInfo.refClass}}
1212
{{else}}
13+
{{#if content}}
1314
import typing
1415
import typing_extensions
1516

17+
{{/if}}
1618
from {{packageName}} import api_client
1719
{{#if schema}}
1820
{{#with schema}}

modules/openapi-json-schema-generator/src/main/resources/python/components/parameters/parameter.hbs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@
1010
{{> _helper_imports }}
1111
{{jsonPathPiece.camelCase}} = {{refInfo.refModule}}.{{refInfo.refClass}}
1212
{{else}}
13+
{{#if content}}
1314
import typing
1415
import typing_extensions
1516

17+
{{/if}}
1618
from {{packageName}} import api_client
1719

1820
{{#if schema}}

modules/openapi-json-schema-generator/src/main/resources/python/components/responses/response.hbs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,22 @@
1111
{{jsonPathPiece.camelCase}} = {{refInfo.refModule}}.{{refInfo.refClass}}
1212
{{else}}
1313
import dataclasses
14+
{{#or content headers}}
15+
{{#if headers}}
1416
import datetime
1517
import decimal
1618
import io
19+
{{/if}}
1720
import typing
21+
{{#if headers}}
1822
import uuid
23+
{{/if}}
1924

25+
{{#if headers}}
2026
import frozendict
27+
{{/if}}
2128
import typing_extensions
29+
{{/or}}
2230
import urllib3
2331

2432
from {{packageName}} import api_client

0 commit comments

Comments
 (0)