Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions modules/openapi-generator/src/main/resources/python/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ from {{packageName}}.exceptions import ( # noqa: F401


{{#operations}}
class {{classname}}(object):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use of (object) as a base class has not been recommended for a long time.

class {{classname}}:
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech

Do not edit the class manually.
"""

def __init__(self, api_client=None):
def __init__(self, api_client=None) -> None:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The return type of -> None is necessary for the type checker to see a newly constructed instances as having a type. Otherwise, we end up with everything being any-typed.

if api_client is None:
api_client = ApiClient.get_default()
self.api_client = api_client
Expand Down Expand Up @@ -65,18 +65,19 @@ class {{classname}}(object):
{{/allParams}}
:param async_req: Whether to execute the request asynchronously.
:type async_req: bool, optional
:param _request_timeout: timeout setting for this request. If one

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This alignment avoids line-length issues (using black's line length configuration).

number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:param _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.
:return: Returns the result object.
If the method is called asynchronously,
returns the request thread.
:rtype: {{returnType}}{{^returnType}}None{{/returnType}}
"""
kwargs['_return_http_data_only'] = True
if '_preload_content' in kwargs:
raise ValueError("Error! Please call the {{operationId}}_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data")
message = "Error! Please call the {{operationId}}_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501
raise ValueError(message)
Comment on lines 79 to 80

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some formatters (e.g. black) will change:

raise ValueError("long string")  # noqa: E501

to:

raise ValueError(
    "long string"
)  # noqa: E501

thereby moving the noqa comment to the wrong location; declaring the message on its own line avoids this problem.

{{#asyncio}}
if async_req is not None:
kwargs['async_req'] = async_req
Expand All @@ -103,7 +104,7 @@ class {{classname}}(object):
:param async_req: Whether to execute the request asynchronously.
:type async_req: bool, optional
:param _preload_content: if False, the ApiResponse.data will
be set to none and raw_data will store the

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

flake8 does not like trailing spaces

be set to none and raw_data will store the
HTTP response body without reading/decoding.
Default is True.
:type _preload_content: bool, optional
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ from {{packageName}} import rest
from {{packageName}}.exceptions import ApiValueError, ApiException


class ApiClient(object):
class ApiClient:
"""Generic API client for OpenAPI client library builds.

OpenAPI generic API client. This client handles the client-
Expand Down Expand Up @@ -56,7 +56,7 @@ class ApiClient(object):
_pool = None

def __init__(self, configuration=None, header_name=None, header_value=None,
cookie=None, pool_threads=1):
cookie=None, pool_threads=1) -> None:
# use default configuration if none is provided
if configuration is None:
configuration = Configuration.get_default()
Expand Down Expand Up @@ -345,7 +345,7 @@ class ApiClient(object):
if data is None:
return None

if type(klass) == str:
if isinstance(klass, str):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was just bad Python (and flake8 notices this)

if klass.startswith('List['):
sub_kls = re.match(r'List\[(.*)]', klass).group(1)
return [self.__deserialize(sub_data, sub_kls)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class ApiResponse:
status_code=None,
headers=None,
data=None,
raw_data=None):
raw_data=None) -> None:
self.status_code = status_code
self.headers = headers
self.data = data
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,20 @@

import unittest

import {{packageName}}
from {{apiPackage}}.{{classFilename}} import {{classname}} # noqa: E501
from {{packageName}}.rest import ApiException
Comment on lines -7 to -9

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not clear what the right behavior is for a test case that is meant to be edited by hand. On the one hand, adding imports for likely usages is helpful; on the other hand, it's not great to generate code that doesn't pass the linter because it includes unnecessary imports.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about commenting out these imports instead so that users can easily uncomment these imports if needed?



class {{#operations}}Test{{classname}}(unittest.TestCase):
"""{{classname}} unit test stubs"""

def setUp(self):
self.api = {{apiPackage}}.{{classFilename}}.{{classname}}() # noqa: E501
def setUp(self) -> None:
self.api = {{classname}}() # noqa: E501

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The import block was importing both the package and the class; we only need one of these. It's more common in Python to use from foo import Bar style so that Bar() can be called without qualification.


def tearDown(self):
def tearDown(self) -> None:
pass

{{#operation}}
def test_{{operationId}}(self):
def test_{{operationId}}(self) -> None:
"""Test case for {{{operationId}}}

{{#summary}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ logger = logging.getLogger(__name__)

class RESTResponse(io.IOBase):

def __init__(self, resp, data):
def __init__(self, resp, data) -> None:
self.aiohttp_response = resp
self.status = resp.status
self.reason = resp.reason
Expand All @@ -33,9 +33,9 @@ class RESTResponse(io.IOBase):
return self.aiohttp_response.headers.get(name, default)


class RESTClientObject(object):
class RESTClientObject:

def __init__(self, configuration, pools_size=4, maxsize=None):
def __init__(self, configuration, pools_size=4, maxsize=None) -> None:

# maxsize is number of requests to host that are allowed in parallel
if maxsize is None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,14 @@ import sys
import urllib3

import http.client as httplib
from {{packageName}}.exceptions import ApiValueError

JSON_SCHEMA_VALIDATION_KEYWORDS = {
'multipleOf', 'maximum', 'exclusiveMaximum',
'minimum', 'exclusiveMinimum', 'maxLength',
'minLength', 'pattern', 'maxItems', 'minItems'
}

class Configuration(object):
class Configuration:
"""This class contains various settings of the API client.

:param host: Base url.
Expand All @@ -45,7 +44,8 @@ class Configuration(object):
configuration.
:param server_operation_variables: Mapping from operation ID to a mapping with
string values to replace variables in templated server configuration.
The validation of enums is performed for variables with defined enum values before.
The validation of enums is performed for variables with defined enum
values before.
:param ssl_ca_cert: str - the path to a file of concatenated CA certificates
in PEM format.

Expand Down Expand Up @@ -146,7 +146,7 @@ conf = {{{packageName}}}.Configuration(
server_index=None, server_variables=None,
server_operation_index=None, server_operation_variables=None,
ssl_ca_cert=None,
):
) -> None:
"""Constructor
"""
self._base_path = "{{{basePath}}}" if host is None else host
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class OpenApiException(Exception):

class ApiTypeError(OpenApiException, TypeError):
def __init__(self, msg, path_to_item=None, valid_classes=None,
key_type=None):
key_type=None) -> None:
""" Raises an exception for TypeErrors

Args:
Expand Down Expand Up @@ -36,7 +36,7 @@ class ApiTypeError(OpenApiException, TypeError):


class ApiValueError(OpenApiException, ValueError):
def __init__(self, msg, path_to_item=None):
def __init__(self, msg, path_to_item=None) -> None:
"""
Args:
msg (str): the exception message
Expand All @@ -54,7 +54,7 @@ class ApiValueError(OpenApiException, ValueError):


class ApiAttributeError(OpenApiException, AttributeError):
def __init__(self, msg, path_to_item=None):
def __init__(self, msg, path_to_item=None) -> None:
"""
Raised when an attribute reference or assignment fails.

Expand All @@ -73,7 +73,7 @@ class ApiAttributeError(OpenApiException, AttributeError):


class ApiKeyError(OpenApiException, KeyError):
def __init__(self, msg, path_to_item=None):
def __init__(self, msg, path_to_item=None) -> None:
"""
Args:
msg (str): the exception message
Expand All @@ -91,7 +91,7 @@ class ApiKeyError(OpenApiException, KeyError):

class ApiException(OpenApiException):

def __init__(self, status=None, reason=None, http_resp=None):
def __init__(self, status=None, reason=None, http_resp=None) -> None:
if http_resp:
self.status = http_resp.status
self.reason = http_resp.reason
Expand All @@ -118,30 +118,30 @@ class ApiException(OpenApiException):

class BadRequestException(ApiException):

def __init__(self, status=None, reason=None, http_resp=None):
def __init__(self, status=None, reason=None, http_resp=None) -> None:
super(BadRequestException, self).__init__(status, reason, http_resp)

class NotFoundException(ApiException):

def __init__(self, status=None, reason=None, http_resp=None):
def __init__(self, status=None, reason=None, http_resp=None) -> None:
super(NotFoundException, self).__init__(status, reason, http_resp)


class UnauthorizedException(ApiException):

def __init__(self, status=None, reason=None, http_resp=None):
def __init__(self, status=None, reason=None, http_resp=None) -> None:
super(UnauthorizedException, self).__init__(status, reason, http_resp)


class ForbiddenException(ApiException):

def __init__(self, status=None, reason=None, http_resp=None):
def __init__(self, status=None, reason=None, http_resp=None) -> None:
super(ForbiddenException, self).__init__(status, reason, http_resp)


class ServiceException(ApiException):

def __init__(self, status=None, reason=None, http_resp=None):
def __init__(self, status=None, reason=None, http_resp=None) -> None:
super(ServiceException, self).__init__(status, reason, http_resp)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
}
{{/discriminator}}

def __init__(self, *args, **kwargs):
def __init__(self, *args, **kwargs) -> None:
if args:
if len(args) > 1:
raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`")
Expand Down Expand Up @@ -177,4 +177,4 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{{.}}}
{{/vendorExtensions.x-py-postponed-model-imports}}
{{classname}}.update_forward_refs()
{{/vendorExtensions.x-py-postponed-model-imports.size}}
{{/vendorExtensions.x-py-postponed-model-imports.size}}
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
}
{{/discriminator}}

def __init__(self, *args, **kwargs):
def __init__(self, *args, **kwargs) -> None:
if args:
if len(args) > 1:
raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`")
Expand Down Expand Up @@ -203,4 +203,4 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}
{{{.}}}
{{/vendorExtensions.x-py-postponed-model-imports}}
{{classname}}.update_forward_refs()
{{/vendorExtensions.x-py-postponed-model-imports.size}}
{{/vendorExtensions.x-py-postponed-model-imports.size}}
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ import datetime

{{#models}}
{{#model}}
import {{packageName}}
from {{modelPackage}}.{{classFilename}} import {{classname}} # noqa: E501
from {{packageName}}.rest import ApiException

class Test{{classname}}(unittest.TestCase):
"""{{classname}} unit test stubs"""
Expand All @@ -21,21 +19,21 @@ class Test{{classname}}(unittest.TestCase):
pass
{{^isEnum}}

def make_instance(self, include_optional):
def make_instance(self, include_optional) -> {{classname}}:
"""Test {{classname}}
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `{{{classname}}}`
"""
model = {{packageName}}.models.{{classFilename}}.{{classname}}() # noqa: E501
if include_optional :
model = {{classname}}() # noqa: E501
if include_optional:
return {{classname}}(
{{#vars}}
{{name}} = {{{example}}}{{^example}}None{{/example}}{{^-last}}, {{/-last}}
{{name}} = {{{example}}}{{^example}}None{{/example}}{{^-last}},{{/-last}}
{{/vars}}
)
else :
else:
return {{classname}}(
{{#vars}}
{{#required}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ logger = logging.getLogger(__name__)

class RESTResponse(io.IOBase):

def __init__(self, resp):
def __init__(self, resp) -> None:
self.urllib3_response = resp
self.status = resp.status
self.reason = resp.reason
Expand All @@ -34,9 +34,9 @@ class RESTResponse(io.IOBase):
return self.urllib3_response.headers.get(name, default)


class RESTClientObject(object):
class RESTClientObject:

def __init__(self, configuration, pools_size=4, maxsize=None):
def __init__(self, configuration, pools_size=4, maxsize=None) -> None:
# urllib3.PoolManager will pass all kw parameters to connectionpool
# https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501
# https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ HASH_SHA256 = 'sha256'
HASH_SHA512 = 'sha512'


class HttpSigningConfiguration(object):
class HttpSigningConfiguration:
"""The configuration parameters for the HTTP signature security scheme.
The HTTP signature security scheme is used to sign HTTP requests with a private key
which is in possession of the API client.
Expand Down Expand Up @@ -112,7 +112,7 @@ class HttpSigningConfiguration(object):
signed_headers=None,
signing_algorithm=None,
hash_algorithm=None,
signature_max_validity=None):
signature_max_validity=None) -> None:
self.key_id = key_id
if signing_scheme not in {SCHEME_HS2019, SCHEME_RSA_SHA256, SCHEME_RSA_SHA512}:
raise Exception("Unsupported security scheme: {0}".format(signing_scheme))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ logger = logging.getLogger(__name__)

class RESTResponse(io.IOBase):

def __init__(self, resp):
def __init__(self, resp) -> None:
self.tornado_response = resp
self.status = resp.code
self.reason = resp.reason
Expand All @@ -39,9 +39,9 @@ class RESTResponse(io.IOBase):
return self.tornado_response.headers.get(name, default)


class RESTClientObject(object):
class RESTClientObject:

def __init__(self, configuration, pools_size=4, maxsize=4):
def __init__(self, configuration, pools_size=4, maxsize=4) -> None:
# maxsize is number of requests to host that are allowed in parallel

self.ca_certs = configuration.ssl_ca_cert
Expand Down
Loading