Skip to content

Commit

Permalink
CTOOLS-68: Ensure pydantic.v1 is updated in all templates
Browse files Browse the repository at this point in the history
  • Loading branch information
Adam Massoud committed May 2, 2024
1 parent 4ccce27 commit b0277a9
Show file tree
Hide file tree
Showing 12 changed files with 1,586 additions and 0 deletions.
313 changes: 313 additions & 0 deletions generate/default_templates/api.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,313 @@
# coding: utf-8

{{>partial_header}}

import re # noqa: F401
import io
import warnings

from pydantic import validate_arguments, ValidationError
{{#asyncio}}
from typing import overload, Optional, Union, Awaitable
{{/asyncio}}

{{#imports}}
{{import}}
{{/imports}}

from {{packageName}}.api_client import ApiClient
from {{packageName}}.api_response import ApiResponse
from {{packageName}}.exceptions import ( # noqa: F401
ApiTypeError,
ApiValueError
)


{{#operations}}
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) -> None:
if api_client is None:
api_client = ApiClient.get_default()
self.api_client = api_client
{{#operation}}

{{#asyncio}}
@overload
async def {{operationId}}(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}**kwargs) -> {{{returnType}}}{{^returnType}}None{{/returnType}}: # noqa: E501
...

@overload
def {{operationId}}(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}async_req: Optional[bool]=True, **kwargs) -> {{{returnType}}}{{^returnType}}None{{/returnType}}: # noqa: E501
...

{{/asyncio}}
@validate_arguments
def {{operationId}}(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}{{#asyncio}}async_req: Optional[bool]=None, {{/asyncio}}**kwargs) -> {{#asyncio}}Union[{{{returnType}}}{{^returnType}}None{{/returnType}}, Awaitable[{{{returnType}}}{{^returnType}}None{{/returnType}}]]{{/asyncio}}{{^asyncio}}{{{returnType}}}{{^returnType}}None{{/returnType}}{{/asyncio}}: # noqa: E501
"""{{#isDeprecated}}(Deprecated) {{/isDeprecated}}{{{summary}}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501

{{#notes}}
{{{.}}} # noqa: E501
{{/notes}}
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True

>>> thread = api.{{operationId}}({{#allParams}}{{paramName}}, {{/allParams}}async_req=True)
>>> result = thread.get()

{{#allParams}}
:param {{paramName}}:{{#description}} {{{.}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}}
:type {{paramName}}: {{dataType}}{{#optional}}, optional{{/optional}}
{{/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 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:
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)
{{#asyncio}}
if async_req is not None:
kwargs['async_req'] = async_req
{{/asyncio}}
return self.{{operationId}}_with_http_info({{#allParams}}{{paramName}}, {{/allParams}}**kwargs) # noqa: E501

@validate_arguments
def {{operationId}}_with_http_info(self, {{#allParams}}{{paramName}} : {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, {{/allParams}}**kwargs) -> ApiResponse: # noqa: E501
"""{{#isDeprecated}}(Deprecated) {{/isDeprecated}}{{{summary}}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501

{{#notes}}
{{{.}}} # noqa: E501
{{/notes}}
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True

>>> thread = api.{{operationId}}_with_http_info({{#allParams}}{{paramName}}, {{/allParams}}async_req=True)
>>> result = thread.get()

{{#allParams}}
:param {{paramName}}:{{#description}} {{{.}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}}
:type {{paramName}}: {{dataType}}{{#optional}}, optional{{/optional}}
{{/allParams}}
: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
HTTP response body without reading/decoding.
Default is True.
:type _preload_content: bool, optional
:param _return_http_data_only: response data instead of ApiResponse
object with status code, headers, etc
:type _return_http_data_only: bool, optional
: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.
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the authentication
in the spec for a single request.
:type _request_auth: dict, optional
:type _content_type: string, optional: force content-type for the request
:return: Returns the result object.
If the method is called asynchronously,
returns the request thread.
:rtype: {{#returnType}}tuple({{.}}, status_code(int), headers(HTTPHeaderDict)){{/returnType}}{{^returnType}}None{{/returnType}}
"""

{{#isDeprecated}}
warnings.warn("{{{httpMethod}}} {{{path}}} is deprecated.", DeprecationWarning)

{{/isDeprecated}}
{{#servers.0}}
_hosts = [
{{#servers}}
'{{{url}}}'{{^-last}},{{/-last}}
{{/servers}}
]
_host = _hosts[0]
if kwargs.get('_host_index'):
_host_index = int(kwargs.get('_host_index'))
if _host_index < 0 or _host_index >= len(_hosts):
raise ApiValueError(
"Invalid host index. Must be 0 <= index < %s"
% len(_host)
)
_host = _hosts[_host_index]
{{/servers.0}}
_params = locals()

_all_params = [
{{#allParams}}
'{{paramName}}'{{^-last}},{{/-last}}
{{/allParams}}
]
_all_params.extend(
[
'async_req',
'_return_http_data_only',
'_preload_content',
'_request_timeout',
'_request_auth',
'_content_type',
'_headers'
]
)

# validate the arguments
for _key, _val in _params['kwargs'].items():
if _key not in _all_params{{#servers.0}} and _key != "_host_index"{{/servers.0}}:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method {{operationId}}" % _key
)
_params[_key] = _val
del _params['kwargs']

_collection_formats = {}

# process the path parameters
_path_params = {}
{{#pathParams}}
if _params['{{paramName}}']:
_path_params['{{baseName}}'] = _params['{{paramName}}']
{{#isArray}}
_collection_formats['{{baseName}}'] = '{{collectionFormat}}'
{{/isArray}}

{{/pathParams}}

# process the query parameters
_query_params = []
{{#queryParams}}
if _params.get('{{paramName}}') is not None: # noqa: E501
{{#isDateTime}}
if isinstance(_params['{{paramName}}'], datetime):
_query_params.append(('{{baseName}}', _params['{{paramName}}'].strftime(self.api_client.configuration.datetime_format)))
else:
_query_params.append(('{{baseName}}', _params['{{paramName}}']))
{{/isDateTime}}
{{^isDateTime}}
{{#isDate}}
if isinstance(_params['{{paramName}}'], date):
_query_params.append(('{{baseName}}', _params['{{paramName}}'].strftime(self.api_client.configuration.date_format)))
else:
_query_params.append(('{{baseName}}', _params['{{paramName}}']))
{{/isDate}}
{{^isDate}}
_query_params.append(('{{baseName}}', _params['{{paramName}}']{{#isEnumRef}}.value{{/isEnumRef}}))
{{/isDate}}
{{/isDateTime}}
{{#isArray}}
_collection_formats['{{baseName}}'] = '{{collectionFormat}}'
{{/isArray}}

{{/queryParams}}
# process the header parameters
_header_params = dict(_params.get('_headers', {}))
{{#headerParams}}
if _params['{{paramName}}']:
_header_params['{{baseName}}'] = _params['{{paramName}}']
{{#isArray}}
_collection_formats['{{baseName}}'] = '{{collectionFormat}}'
{{/isArray}}

{{/headerParams}}
# process the form parameters
_form_params = []
_files = {}
{{#formParams}}
if _params['{{paramName}}']:
{{^isFile}}
_form_params.append(('{{{baseName}}}', _params['{{paramName}}']))
{{/isFile}}
{{#isFile}}
_files['{{{baseName}}}'] = _params['{{paramName}}']
{{/isFile}}
{{#isArray}}
_collection_formats['{{{baseName}}}'] = '{{collectionFormat}}'
{{/isArray}}

{{/formParams}}
# process the body parameter
_body_params = None
{{#bodyParam}}
if _params['{{paramName}}'] is not None:
_body_params = _params['{{paramName}}']
{{#isBinary}}
# convert to byte array if the input is a file name (str)
if isinstance(_body_params, str):
with io.open(_body_params, "rb") as _fp:
_body_params_from_file = _fp.read()
_body_params = _body_params_from_file
{{/isBinary}}

{{/bodyParam}}
{{#hasProduces}}
# set the HTTP header `Accept`
_header_params['Accept'] = self.api_client.select_header_accept(
[{{#produces}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/produces}}]) # noqa: E501

{{/hasProduces}}
{{#hasConsumes}}
# set the HTTP header `Content-Type`
_content_types_list = _params.get('_content_type',
self.api_client.select_header_content_type(
[{{#consumes}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/consumes}}]))
if _content_types_list:
_header_params['Content-Type'] = _content_types_list

{{/hasConsumes}}
# authentication setting
_auth_settings = [{{#authMethods}}'{{name}}'{{^-last}}, {{/-last}}{{/authMethods}}] # noqa: E501

{{#returnType}}
{{#responses}}
{{#-first}}
_response_types_map = {
{{/-first}}
{{^isWildcard}}
'{{code}}': {{#dataType}}"{{.}}"{{/dataType}}{{^dataType}}None{{/dataType}},
{{/isWildcard}}
{{#-last}}
}
{{/-last}}
{{/responses}}
{{/returnType}}
{{^returnType}}
_response_types_map = {}
{{/returnType}}

return self.api_client.call_api(
'{{{path}}}', '{{httpMethod}}',
_path_params,
_query_params,
_header_params,
body=_body_params,
post_params=_form_params,
files=_files,
response_types_map=_response_types_map,
auth_settings=_auth_settings,
async_req=_params.get('async_req'),
_return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501
_preload_content=_params.get('_preload_content', True),
_request_timeout=_params.get('_request_timeout'),
{{#servers.0}}
_host=_host,
{{/servers.0}}
collection_formats=_collection_formats,
_request_auth=_params.get('_request_auth'))
{{/operation}}
{{/operations}}
25 changes: 25 additions & 0 deletions generate/default_templates/api_response.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""API response object."""

from __future__ import annotations
from typing import Any, Dict, Optional
from pydantic import Field, StrictInt, StrictStr

class ApiResponse:
"""
API response object
"""

status_code: Optional[StrictInt] = Field(None, description="HTTP status code")
headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers")
data: Optional[Any] = Field(None, description="Deserialized data given the data type")
raw_data: Optional[Any] = Field(None, description="Raw data (HTTP response body)")

def __init__(self,
status_code=None,
headers=None,
data=None,
raw_data=None) -> None:
self.status_code = status_code
self.headers = headers
self.data = data
self.raw_data = raw_data
Loading

0 comments on commit b0277a9

Please sign in to comment.