Skip to content

[Python] better handling of model name #2309

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 4, 2016
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
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
public class CodegenModel {
public String parent, parentSchema;
public String name, classname, description, classVarName, modelJson, dataType;
public String classFilename; // store the class file name, mainly used for import
public String unescapedDescription;
public String discriminator;
public String defaultValue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -877,6 +877,7 @@ public CodegenModel fromModel(String name, Model model, Map<String, Model> allDe
m.unescapedDescription = model.getDescription();
m.classname = toModelName(name);
m.classVarName = toVarName(name);
m.classFilename = toModelFilename(name);
m.modelJson = Json.pretty(model);
m.externalDocs = model.getExternalDocs();
m.vendorExtensions = model.getVendorExtensions();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,7 @@ public String toParamName(String name) {

@Override
public String toModelName(String name) {
name = sanitizeName(modelNamePrefix + name + modelNameSuffix); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.

name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// remove dollar sign
name = name.replaceAll("$", "");

Expand All @@ -223,13 +222,25 @@ public String toModelName(String name) {
name = "object_" + name; // e.g. return => ObjectReturn (after camelize)
}

if (!StringUtils.isEmpty(modelNamePrefix)) {
name = modelNamePrefix + "_" + name;
}

if (!StringUtils.isEmpty(modelNameSuffix)) {
name = name + "_" + modelNameSuffix;
}

// camelize the model name
// phone_number => PhoneNumber
return camelize(name);
}

@Override
public String toModelFilename(String name) {
name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
// remove dollar sign
name = name.replaceAll("$", "");

// model name cannot use reserved keyword, e.g. return
if (isReservedWord(name)) {
LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + underscore(dropDots("object_" + name)));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from __future__ import absolute_import

# import models into model package
{{#models}}{{#model}}from .{{classVarName}} import {{classname}}{{/model}}
{{#models}}{{#model}}from .{{classFilename}} import {{classname}}{{/model}}
{{/models}}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import absolute_import

# import models into sdk package
{{#models}}{{#model}}from .models.{{classVarName}} import {{classname}}
{{#models}}{{#model}}from .models.{{classFilename}} import {{classname}}
{{/model}}{{/models}}
# import apis into sdk package
{{#apiInfo}}{{#apis}}from .apis.{{classVarName}} import {{classname}}
Expand Down
22 changes: 22 additions & 0 deletions modules/swagger-codegen/src/test/resources/2_0/petstore.json
Original file line number Diff line number Diff line change
Expand Up @@ -1251,6 +1251,28 @@
"xml": {
"name": "Order"
}
},
"$special[model.name]": {
"properties": {
"$special[property.name]": {
"type": "integer",
"format": "int64"
}
},
"xml": {
"name": "$special[model.name]"
}
},
"Return": {
"properties": {
"return": {
"type": "integer",
"format": "int32"
}
},
"xml": {
"name": "Return"
}
}
}
}
3 changes: 3 additions & 0 deletions samples/client/petstore/python/swagger_client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
from .models.category import Category
from .models.pet import Pet
from .models.tag import Tag
from .models.object_return import ObjectReturn
from .models.order import Order
from .models.special_model_name import SpecialModelName
from .models.inline_response_200 import InlineResponse200

# import apis into sdk package
from .apis.user_api import UserApi
Expand Down
77 changes: 77 additions & 0 deletions samples/client/petstore/python/swagger_client/apis/pet_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,83 @@ def upload_file(self, pet_id, **kwargs):
callback=params.get('callback'))
return response

def get_pet_by_id_in_object(self, pet_id, **kwargs):
"""
Fake endpoint to test inline arbitrary object return by 'Find pet by ID'
Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions

This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_pet_by_id_in_object(pet_id, callback=callback_function)

:param callback function: The callback function
for asynchronous request. (optional)
:param int pet_id: ID of pet that needs to be fetched (required)
:return: InlineResponse200
If the method is called asynchronously,
returns the request thread.
"""

all_params = ['pet_id']
all_params.append('callback')

params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_pet_by_id_in_object" % key
)
params[key] = val
del params['kwargs']

# verify the required parameter 'pet_id' is set
if ('pet_id' not in params) or (params['pet_id'] is None):
raise ValueError("Missing the required parameter `pet_id` when calling `get_pet_by_id_in_object`")

resource_path = '/pet/{petId}?response=inline_arbitrary_object'.replace('{format}', 'json')
path_params = {}
if 'pet_id' in params:
path_params['petId'] = params['pet_id']

query_params = {}

header_params = {}

form_params = []
local_var_files = {}

body_params = None

# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']

# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type([])

# Authentication setting
auth_settings = ['api_key', 'petstore_auth']

response = self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='InlineResponse200',
auth_settings=auth_settings,
callback=params.get('callback'))
return response

def pet_pet_idtesting_byte_arraytrue_get(self, pet_id, **kwargs):
"""
Fake endpoint to test byte array return by 'Find pet by ID'
Expand Down
71 changes: 71 additions & 0 deletions samples/client/petstore/python/swagger_client/apis/store_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,77 @@ def get_inventory(self, **kwargs):
callback=params.get('callback'))
return response

def get_inventory_in_object(self, **kwargs):
"""
Fake endpoint to test arbitrary object return by 'Get inventory'
Returns an arbitrary object which is actually a map of status codes to quantities

This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_inventory_in_object(callback=callback_function)

:param callback function: The callback function
for asynchronous request. (optional)
:return: object
If the method is called asynchronously,
returns the request thread.
"""

all_params = []
all_params.append('callback')

params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_inventory_in_object" % key
)
params[key] = val
del params['kwargs']


resource_path = '/store/inventory?response=arbitrary_object'.replace('{format}', 'json')
path_params = {}

query_params = {}

header_params = {}

form_params = []
local_var_files = {}

body_params = None

# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']

# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type([])

# Authentication setting
auth_settings = ['api_key']

response = self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='object',
auth_settings=auth_settings,
callback=params.get('callback'))
return response

def place_order(self, **kwargs):
"""
Place an order for a pet
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,7 @@
from .category import Category
from .pet import Pet
from .tag import Tag
from .object_return import ObjectReturn
from .order import Order
from .special_model_name import SpecialModelName
from .inline_response_200 import InlineResponse200