From f0e09ae33a60c93edd0083710ce8663614b207af Mon Sep 17 00:00:00 2001 From: geekerzp Date: Thu, 16 Jul 2015 17:24:42 +0800 Subject: [PATCH 1/9] Add enum support for model property of python client --- .../src/main/resources/python/api.mustache | 3 +- .../main/resources/python/api_client.mustache | 2 +- .../src/main/resources/python/model.mustache | 14 ++- .../python/swagger_client/api_client.py | 2 +- .../python/swagger_client/apis/pet_api.py | 4 - .../python/swagger_client/apis/store_api.py | 2 - .../python/swagger_client/apis/user_api.py | 3 - .../python/swagger_client/models/category.py | 22 ++++- .../python/swagger_client/models/order.py | 69 +++++++++++++-- .../python/swagger_client/models/pet.py | 69 +++++++++++++-- .../python/swagger_client/models/tag.py | 22 ++++- .../python/swagger_client/models/user.py | 88 +++++++++++++++++-- .../petstore/python/tests/test_order_model.py | 25 ++++++ 13 files changed, 287 insertions(+), 38 deletions(-) create mode 100644 samples/client/petstore/python/tests/test_order_model.py diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 8c9e719e005..2525497b326 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -51,8 +51,7 @@ class {{classname}}(object): {{/allParams}} :return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}} """ - {{#allParams}}{{#required}} - # verify the required parameter '{{paramName}}' is set + {{#allParams}}{{#required}}# verify the required parameter '{{paramName}}' is set if {{paramName}} is None: raise ValueError("Missing the required parameter `{{paramName}}` when calling `{{nickname}}`") {{/required}}{{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 9188c851327..d6fe9c3793f 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -149,7 +149,7 @@ class ApiClient(object): # Convert model obj to dict except attributes `swagger_types`, `attribute_map` # and attributes which value is not None. # Convert attribute name to json key in model definition for request. - obj_dict = {obj.attribute_map[key]: val + obj_dict = {obj.attribute_map[key[1:]]: val for key, val in iteritems(obj.__dict__) if key != 'swagger_types' and key != 'attribute_map' and val is not None} return {key: self.sanitize_for_serialization(val) diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 429eac33ec5..3dda53963a3 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -43,9 +43,21 @@ class {{classname}}(object): } {{#vars}} {{#description}}# {{description}}{{/description}} - self.{{name}} = None # {{{datatype}}} + self._{{name}} = None # {{{datatype}}} {{/vars}} + {{#vars}} + @property + def {{name}}(self): + return self._{{name}} + @{{name}}.setter + def {{name}}(self, {{name}}): + {{#isEnum}}allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] + if {{name}} not in allowed_values: + raise ValueError("Invalid value for `{{name}}`, must be one of {0}".format(allowed_values)) + {{/isEnum}} + self._{{name}} = {{name}} + {{/vars}} def __repr__(self): properties = [] for p in self.__dict__: diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/swagger_client/api_client.py index 9188c851327..d6fe9c3793f 100644 --- a/samples/client/petstore/python/swagger_client/api_client.py +++ b/samples/client/petstore/python/swagger_client/api_client.py @@ -149,7 +149,7 @@ class ApiClient(object): # Convert model obj to dict except attributes `swagger_types`, `attribute_map` # and attributes which value is not None. # Convert attribute name to json key in model definition for request. - obj_dict = {obj.attribute_map[key]: val + obj_dict = {obj.attribute_map[key[1:]]: val for key, val in iteritems(obj.__dict__) if key != 'swagger_types' and key != 'attribute_map' and val is not None} return {key: self.sanitize_for_serialization(val) diff --git a/samples/client/petstore/python/swagger_client/apis/pet_api.py b/samples/client/petstore/python/swagger_client/apis/pet_api.py index 683e807adb9..656ce8a5768 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -258,7 +258,6 @@ class PetApi(object): :return: Pet """ - # verify the required parameter 'pet_id' is set if pet_id is None: raise ValueError("Missing the required parameter `pet_id` when calling `get_pet_by_id`") @@ -317,7 +316,6 @@ class PetApi(object): :return: None """ - # verify the required parameter 'pet_id' is set if pet_id is None: raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`") @@ -379,7 +377,6 @@ class PetApi(object): :return: None """ - # verify the required parameter 'pet_id' is set if pet_id is None: raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") @@ -439,7 +436,6 @@ class PetApi(object): :return: None """ - # verify the required parameter 'pet_id' is set if pet_id is None: raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") diff --git a/samples/client/petstore/python/swagger_client/apis/store_api.py b/samples/client/petstore/python/swagger_client/apis/store_api.py index 06775fdc860..e1e825d1c6c 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/swagger_client/apis/store_api.py @@ -152,7 +152,6 @@ class StoreApi(object): :return: Order """ - # verify the required parameter 'order_id' is set if order_id is None: raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`") @@ -209,7 +208,6 @@ class StoreApi(object): :return: None """ - # verify the required parameter 'order_id' is set if order_id is None: raise ValueError("Missing the required parameter `order_id` when calling `delete_order`") diff --git a/samples/client/petstore/python/swagger_client/apis/user_api.py b/samples/client/petstore/python/swagger_client/apis/user_api.py index 8299a95c2a0..ba0fd5e0f1c 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/swagger_client/apis/user_api.py @@ -307,7 +307,6 @@ class UserApi(object): :return: User """ - # verify the required parameter 'username' is set if username is None: raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") @@ -365,7 +364,6 @@ class UserApi(object): :return: None """ - # verify the required parameter 'username' is set if username is None: raise ValueError("Missing the required parameter `username` when calling `update_user`") @@ -423,7 +421,6 @@ class UserApi(object): :return: None """ - # verify the required parameter 'username' is set if username is None: raise ValueError("Missing the required parameter `username` when calling `delete_user`") diff --git a/samples/client/petstore/python/swagger_client/models/category.py b/samples/client/petstore/python/swagger_client/models/category.py index cfd69ee955c..f2be305118d 100644 --- a/samples/client/petstore/python/swagger_client/models/category.py +++ b/samples/client/petstore/python/swagger_client/models/category.py @@ -41,12 +41,30 @@ class Category(object): } - self.id = None # int + self._id = None # int - self.name = None # str + self._name = None # str + + @property + def id(self): + return self._id + @id.setter + def id(self, id): + + self._id = id + + @property + def name(self): + return self._name + + @name.setter + def name(self, name): + + self._name = name + def __repr__(self): properties = [] for p in self.__dict__: diff --git a/samples/client/petstore/python/swagger_client/models/order.py b/samples/client/petstore/python/swagger_client/models/order.py index 2e448f5f425..34774c6c96c 100644 --- a/samples/client/petstore/python/swagger_client/models/order.py +++ b/samples/client/petstore/python/swagger_client/models/order.py @@ -49,24 +49,81 @@ class Order(object): } - self.id = None # int + self._id = None # int - self.pet_id = None # int + self._pet_id = None # int - self.quantity = None # int + self._quantity = None # int - self.ship_date = None # datetime + self._ship_date = None # datetime # Order Status - self.status = None # str + self._status = None # str - self.complete = None # bool + self._complete = None # bool + + @property + def id(self): + return self._id + @id.setter + def id(self, id): + + self._id = id + + @property + def pet_id(self): + return self._pet_id + + @pet_id.setter + def pet_id(self, pet_id): + + self._pet_id = pet_id + + @property + def quantity(self): + return self._quantity + + @quantity.setter + def quantity(self, quantity): + + self._quantity = quantity + + @property + def ship_date(self): + return self._ship_date + + @ship_date.setter + def ship_date(self, ship_date): + + self._ship_date = ship_date + + @property + def status(self): + return self._status + + @status.setter + def status(self, status): + allowed_values = ["placed", "approved", "delivered"] + if status not in allowed_values: + raise ValueError("Invalid value for `status`, must be one of {0}".format(allowed_values)) + + self._status = status + + @property + def complete(self): + return self._complete + + @complete.setter + def complete(self, complete): + + self._complete = complete + def __repr__(self): properties = [] for p in self.__dict__: diff --git a/samples/client/petstore/python/swagger_client/models/pet.py b/samples/client/petstore/python/swagger_client/models/pet.py index a943b639663..37a4ca89b45 100644 --- a/samples/client/petstore/python/swagger_client/models/pet.py +++ b/samples/client/petstore/python/swagger_client/models/pet.py @@ -49,24 +49,81 @@ class Pet(object): } - self.id = None # int + self._id = None # int - self.category = None # Category + self._category = None # Category - self.name = None # str + self._name = None # str - self.photo_urls = None # list[str] + self._photo_urls = None # list[str] - self.tags = None # list[Tag] + self._tags = None # list[Tag] # pet status in the store - self.status = None # str + self._status = None # str + + @property + def id(self): + return self._id + @id.setter + def id(self, id): + + self._id = id + + @property + def category(self): + return self._category + + @category.setter + def category(self, category): + + self._category = category + + @property + def name(self): + return self._name + + @name.setter + def name(self, name): + + self._name = name + + @property + def photo_urls(self): + return self._photo_urls + + @photo_urls.setter + def photo_urls(self, photo_urls): + + self._photo_urls = photo_urls + + @property + def tags(self): + return self._tags + + @tags.setter + def tags(self, tags): + + self._tags = tags + + @property + def status(self): + return self._status + + @status.setter + def status(self, status): + allowed_values = ["available", "pending", "sold"] + if status not in allowed_values: + raise ValueError("Invalid value for `status`, must be one of {0}".format(allowed_values)) + + self._status = status + def __repr__(self): properties = [] for p in self.__dict__: diff --git a/samples/client/petstore/python/swagger_client/models/tag.py b/samples/client/petstore/python/swagger_client/models/tag.py index 6347352eba7..63c1f3291b9 100644 --- a/samples/client/petstore/python/swagger_client/models/tag.py +++ b/samples/client/petstore/python/swagger_client/models/tag.py @@ -41,12 +41,30 @@ class Tag(object): } - self.id = None # int + self._id = None # int - self.name = None # str + self._name = None # str + + @property + def id(self): + return self._id + @id.setter + def id(self, id): + + self._id = id + + @property + def name(self): + return self._name + + @name.setter + def name(self, name): + + self._name = name + def __repr__(self): properties = [] for p in self.__dict__: diff --git a/samples/client/petstore/python/swagger_client/models/user.py b/samples/client/petstore/python/swagger_client/models/user.py index 83efcd9ee2b..7049e1e8c97 100644 --- a/samples/client/petstore/python/swagger_client/models/user.py +++ b/samples/client/petstore/python/swagger_client/models/user.py @@ -53,30 +53,102 @@ class User(object): } - self.id = None # int + self._id = None # int - self.username = None # str + self._username = None # str - self.first_name = None # str + self._first_name = None # str - self.last_name = None # str + self._last_name = None # str - self.email = None # str + self._email = None # str - self.password = None # str + self._password = None # str - self.phone = None # str + self._phone = None # str # User Status - self.user_status = None # int + self._user_status = None # int + + @property + def id(self): + return self._id + @id.setter + def id(self, id): + + self._id = id + + @property + def username(self): + return self._username + + @username.setter + def username(self, username): + + self._username = username + + @property + def first_name(self): + return self._first_name + + @first_name.setter + def first_name(self, first_name): + + self._first_name = first_name + + @property + def last_name(self): + return self._last_name + + @last_name.setter + def last_name(self, last_name): + + self._last_name = last_name + + @property + def email(self): + return self._email + + @email.setter + def email(self, email): + + self._email = email + + @property + def password(self): + return self._password + + @password.setter + def password(self, password): + + self._password = password + + @property + def phone(self): + return self._phone + + @phone.setter + def phone(self, phone): + + self._phone = phone + + @property + def user_status(self): + return self._user_status + + @user_status.setter + def user_status(self, user_status): + + self._user_status = user_status + def __repr__(self): properties = [] for p in self.__dict__: diff --git a/samples/client/petstore/python/tests/test_order_model.py b/samples/client/petstore/python/tests/test_order_model.py new file mode 100644 index 00000000000..e411ca0103d --- /dev/null +++ b/samples/client/petstore/python/tests/test_order_model.py @@ -0,0 +1,25 @@ +# coding: utf-8 + +""" +Run the tests. +$ pip install nose (optional) +$ cd swagger_client-python +$ nosetests -v +""" + +import os +import time +import unittest + +import swagger_client + + +class OrderModelTests(unittest.TestCase): + + def test_status(self): + order = swagger_client.Order() + order.status = "placed" + self.assertEqual("placed", order.status) + + with self.assertRaises(ValueError): + order.status = "invalid" From 3993ef3dc8c2c6b88c1361324f7b5ccf5db9390c Mon Sep 17 00:00:00 2001 From: geekerzp Date: Thu, 16 Jul 2015 18:58:23 +0800 Subject: [PATCH 2/9] Update python codegen. Remove leading underscore. --- .../io/swagger/codegen/languages/PythonClientCodegen.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index c0430515201..8f78f2e1d49 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -117,7 +117,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String escapeReservedWord(String name) { - return "_" + name; + return name + "_"; } @Override @@ -160,8 +160,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig } public String toDefaultValue(Property p) { - // TODO: Support Python def value - return "null"; + return "None"; } @Override @@ -183,6 +182,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig name = escapeReservedWord(name); } + // remove leading underscore + name = name.replaceAll("^_*", ""); + return name; } From 60d6cd744a56aebcd3cc869fc6393fd21863cfe9 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 18 Jul 2015 14:30:19 +0800 Subject: [PATCH 3/9] Format python client using pep8 --- .../resources/python/__init__api.mustache | 7 +- .../resources/python/__init__model.mustache | 4 +- .../src/main/resources/python/api.mustache | 83 +- .../main/resources/python/api_client.mustache | 807 ++++++++++-------- .../resources/python/configuration.mustache | 47 +- .../src/main/resources/python/model.mustache | 38 +- .../src/main/resources/python/rest.mustache | 36 +- .../python/swagger_client/api_client.py | 807 ++++++++++-------- .../python/swagger_client/apis/__init__.py | 1 - .../python/swagger_client/apis/pet_api.py | 411 +++++---- .../python/swagger_client/apis/store_api.py | 205 +++-- .../python/swagger_client/apis/user_api.py | 405 +++++---- .../python/swagger_client/configuration.py | 27 +- .../python/swagger_client/models/__init__.py | 1 - .../python/swagger_client/models/category.py | 34 +- .../python/swagger_client/models/order.py | 67 +- .../python/swagger_client/models/pet.py | 67 +- .../python/swagger_client/models/tag.py | 34 +- .../python/swagger_client/models/user.py | 76 +- .../petstore/python/swagger_client/rest.py | 36 +- 20 files changed, 1802 insertions(+), 1391 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/__init__api.mustache b/modules/swagger-codegen/src/main/resources/python/__init__api.mustache index b4442b736ff..989a5ea8382 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__api.mustache @@ -1,5 +1,8 @@ from __future__ import absolute_import # import apis into api package -{{#apiInfo}}{{#apis}}from .{{classVarName}} import {{classname}} -{{/apis}}{{/apiInfo}} +{{#apiInfo}} +{{#apis}} +from .{{classVarName}} import {{classname}} +{{/apis}} +{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/python/__init__model.mustache b/modules/swagger-codegen/src/main/resources/python/__init__model.mustache index 7a3f1866ea7..734e0692350 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__model.mustache @@ -1,5 +1,5 @@ from __future__ import absolute_import # import models into model package -{{#models}}{{#model}}from .{{classVarName}} import {{classname}} -{{/model}}{{/models}} +{{#models}}{{#model}}from .{{classVarName}} import {{classname}}{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 54ca668d996..94f5af1ffcc 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -17,7 +17,8 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ from __future__ import absolute_import @@ -30,6 +31,7 @@ from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient + {{#operations}} class {{classname}}(object): @@ -41,37 +43,48 @@ class {{classname}}(object): if not config.api_client: config.api_client = ApiClient('{{basePath}}') self.api_client = config.api_client - - {{#operation}} +{{#operation}} + def {{nickname}}(self, {{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}**kwargs): """ {{{summary}}} {{{notes}}} - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) - {{#allParams}}:param {{dataType}} {{paramName}}: {{{description}}} {{#required}}(required){{/required}}{{#optional}}(optional){{/optional}} - {{/allParams}} + :param callback function: The callback function + for asynchronous request. (optional) +{{#allParams}} + :param {{dataType}} {{paramName}}: {{{description}}} {{#required}}(required){{/required}}{{#optional}}(optional){{/optional}} +{{/allParams}} :return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}} - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - {{#allParams}}{{#required}}# verify the required parameter '{{paramName}}' is set +{{#allParams}} +{{#required}} + # verify the required parameter '{{paramName}}' is set if {{paramName}} is None: raise ValueError("Missing the required parameter `{{paramName}}` when calling `{{nickname}}`") - {{/required}}{{/allParams}} +{{/required}} +{{/allParams}} + all_params = [{{#allParams}}'{{paramName}}'{{#hasMore}}, {{/hasMore}}{{/allParams}}] 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 {{nickname}}" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method {{nickname}}" % key + ) params[key] = val del params['kwargs'] @@ -79,45 +92,59 @@ class {{classname}}(object): method = '{{httpMethod}}' path_params = {} - {{#pathParams}} +{{#pathParams}} if '{{paramName}}' in params: - path_params['{{baseName}}'] = params['{{paramName}}'] - {{/pathParams}} + path_params['{{baseName}}'] = params['{{paramName}}'] +{{/pathParams}} + query_params = {} - {{#queryParams}} +{{#queryParams}} if '{{paramName}}' in params: query_params['{{baseName}}'] = params['{{paramName}}'] - {{/queryParams}} +{{/queryParams}} + header_params = {} - {{#headerParams}} +{{#headerParams}} if '{{paramName}}' in params: header_params['{{baseName}}'] = params['{{paramName}}'] - {{/headerParams}} +{{/headerParams}} + form_params = {} files = {} - {{#formParams}} +{{#formParams}} if '{{paramName}}' in params: {{#notFile}}form_params['{{baseName}}'] = params['{{paramName}}']{{/notFile}}{{#isFile}}files['{{baseName}}'] = params['{{paramName}}']{{/isFile}} - {{/formParams}} +{{/formParams}} + body_params = None - {{#bodyParam}} +{{#bodyParam}} if '{{paramName}}' in params: body_params = params['{{paramName}}'] - {{/bodyParam}} +{{/bodyParam}} + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept([{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]) + header_params['Accept'] = self.api_client.\ + select_header_accept([{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type([{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]) # Authentication setting auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, + auth_settings=auth_settings, + callback=params.get('callback')) return response - {{/operation}} +{{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 4ee306581ba..37bf1be69c0 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -27,415 +27,480 @@ from datetime import date from six import iteritems try: - # for python3 - from urllib.parse import quote + # for python3 + from urllib.parse import quote except ImportError: - # for python2 - from urllib import quote + # for python2 + from urllib import quote from .configuration import Configuration + class ApiClient(object): - """ - Generic API client for Swagger client library builds - - :param host: The base path for the server to call - :param header_name: a header to pass when making calls to the API - :param header_value: a header value to pass when making calls to the API - """ - def __init__(self, host=Configuration().host, header_name=None, header_value=None): - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.host = host - self.cookie = None - # Set default User-Agent. - self.user_agent = 'Python-Swagger' - - @property - def user_agent(self): - return self.default_headers['User-Agent'] - - @user_agent.setter - def user_agent(self, value): - self.default_headers['User-Agent'] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - def __call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None): - - # headers parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params['Cookie'] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - for k, v in iteritems(path_params): - replacement = quote(str(self.to_path_value(v))) - resource_path = resource_path.replace('{' + k + '}', replacement) - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = {k: self.to_path_value(v) for k, v in iteritems(query_params)} - - # post parameters - if post_params: - post_params = self.prepare_post_parameters(post_params, files) - post_params = self.sanitize_for_serialization(post_params) - - # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # request url - url = self.host + resource_path - - # perform request and return response - response_data = self.request(method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body) - - self.last_response = response_data - - # deserialize response data - if response_type: - deserialized_data = self.deserialize(response_data, response_type) - else: - deserialized_data = None - - if callback: - callback(deserialized_data) - else: - return deserialized_data - - def to_path_value(self, obj): """ - Convert a string or object to a path-friendly value + Generic API client for Swagger client library builds - :param obj: object or string value - - :return string: quoted value + :param host: The base path for the server to call + :param header_name: a header to pass when making calls to the API + :param header_value: a header value to pass when making calls to the API """ - if type(obj) == list: - return ','.join(obj) - else: - return str(obj) + def __init__(self, host=Configuration().host, + header_name=None, header_value=None): - def sanitize_for_serialization(self, obj): - """ - Sanitize an object for Request. + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.host = host + self.cookie = None + # Set default User-Agent. + self.user_agent = 'Python-Swagger' - If obj is None, return None. - If obj is str, int, float, bool, return directly. - If obj is datetime.datetime, datetime.date convert to string in iso8601 format. - If obj is list, santize each element in the list. - If obj is dict, return the dict. - If obj is swagger model, return the properties dict. - """ - if isinstance(obj, type(None)): - return None - elif isinstance(obj, (str, int, float, bool, tuple)): - return obj - elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] - elif isinstance(obj, (datetime, date)): - return obj.isoformat() - else: - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in model definition for request. - obj_dict = {obj.attribute_map[key[1:]]: val - for key, val in iteritems(obj.__dict__) - if key != 'swagger_types' and key != 'attribute_map' and val is not None} - return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} + @property + def user_agent(self): + return self.default_headers['User-Agent'] - def deserialize(self, response, response_type): - """ - Derialize response into an object. + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value - :param response: RESTResponse object to be deserialized - :param response_type: class literal for deserialzied object, or string of class name + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value - :return: deserialized object - """ - # handle file downloading - save response body into a tmp file and return the instance - if "file" == response_type: - return self.__deserialize_file(response) + def __call_api(self, resource_path, method, + path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, + response_type=None, auth_settings=None, callback=None): - # fetch data from response object - try: - data = json.loads(response.data) - except ValueError: - data = response.data + # headers parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) - return self.__deserialize(data, response_type) + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + for k, v in iteritems(path_params): + replacement = quote(str(self.to_path_value(v))) + resource_path = resource_path.\ + replace('{' + k + '}', replacement) - def __deserialize(self, data, klass): - """ - :param data: dict, list or str - :param klass: class literal, or string of class name + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + query_params = {k: self.to_path_value(v) + for k, v in iteritems(query_params)} - :return: object - """ - if data is None: - return None + # post parameters + if post_params: + post_params = self.prepare_post_parameters(post_params, files) + post_params = self.sanitize_for_serialization(post_params) - if type(klass) == str: - if 'list[' in klass: - sub_kls = re.match('list\[(.*)\]', klass).group(1) - return [self.__deserialize(sub_data, sub_kls) for sub_data in data] + # auth setting + self.update_params_for_auth(header_params, query_params, auth_settings) - if 'dict(' in klass: - sub_kls = re.match('dict\((.*), (.*)\)', klass).group(2) - return {k: self.__deserialize(v, sub_kls) for k, v in iteritems(data)} + # body + if body: + body = self.sanitize_for_serialization(body) - # convert str to class - # for native types - if klass in ['int', 'float', 'str', 'bool', "date", 'datetime', "object"]: - klass = eval(klass) - # for model types - else: - klass = eval('models.' + klass) + # request url + url = self.host + resource_path - if klass in [int, float, str, bool]: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object() - elif klass == date: - return self.__deserialize_date(data) - elif klass == datetime: - return self.__deserialize_datatime(data) - else: - return self.__deserialize_model(data, klass) + # perform request and return response + response_data = self.request(method, url, + query_params=query_params, + headers=header_params, + post_params=post_params, body=body) - def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_type=None, auth_settings=None, callback=None): - """ - Perform http request and return deserialized data + self.last_response = response_data - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, for `multipart/form-data`. - :param callback function: Callback function for asynchronous request. - If provide this parameter, the request will be called asynchronously. - :return: - If provide parameter callback, the request will be called asynchronously. - The method will return the request thread. - If parameter callback is None, then the method will return the response directly. - """ - if callback is None: - return self.__call_api(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_type, auth_settings, callback) - else: - thread = threading.Thread(target=self.__call_api, - args=(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_type, auth_settings, callback)) - thread.start() - return thread - - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None): - """ - Perform http request using RESTClient. - """ - if method == "GET": - return RESTClient.GET(url, query_params=query_params, headers=headers) - elif method == "HEAD": - return RESTClient.HEAD(url, query_params=query_params, headers=headers) - elif method == "POST": - return RESTClient.POST(url, headers=headers, post_params=post_params, body=body) - elif method == "PUT": - return RESTClient.PUT(url, headers=headers, post_params=post_params, body=body) - elif method == "PATCH": - return RESTClient.PATCH(url, headers=headers, post_params=post_params, body=body) - elif method == "DELETE": - return RESTClient.DELETE(url, query_params=query_params, headers=headers) - else: - raise ValueError("http method must be `GET`, `HEAD`, `POST`, `PATCH`, `PUT` or `DELETE`") - - def prepare_post_parameters(self, post_params=None, files=None): - params = {} - - if post_params: - params.update(post_params) - - if files: - for k, v in iteritems(files): - if v: - with open(v, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' - params[k] = tuple([filename, filedata, mimetype]) - - return params - - def select_header_accept(self, accepts): - """ - Return `Accept` based on an array of accepts provided - """ - if not accepts: - return - - accepts = list(map(lambda x: x.lower(), accepts)) - - if 'application/json' in accepts: - return 'application/json' - else: - return ', '.join(accepts) - - def select_header_content_type(self, content_types): - """ - Return `Content-Type` baseed on an array of content_types provided - """ - if not content_types: - return 'application/json' - - content_types = list(map(lambda x: x.lower(), content_types)) - - if 'application/json' in content_types: - return 'application/json' - else: - return content_types[0] - - def update_params_for_auth(self, headers, querys, auth_settings): - """ - Update header and query params based on authentication setting - """ - config = Configuration() - - if not auth_settings: - return - - for auth in auth_settings: - auth_setting = config.auth_settings().get(auth) - if auth_setting: - if auth_setting['in'] == 'header': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - querys[auth_setting['key']] = auth_setting['value'] + # deserialize response data + if response_type: + deserialized_data = self.deserialize(response_data, response_type) else: - raise ValueError('Authentication token must be in `query` or `header`') + deserialized_data = None - def __deserialize_file(self, response): - """ - Save response body into a file in (the defined) temporary folder, using the filename - from the `Content-Disposition` header if provided, otherwise a random filename. + if callback: + callback(deserialized_data) + else: + return deserialized_data - :param response: RESTResponse - :return: file path - """ - fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) - os.close(fd) - os.remove(path) + def to_path_value(self, obj): + """ + Convert a string or object to a path-friendly value - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).group(1) - path = os.path.join(os.path.dirname(path), filename) + :param obj: object or string value - with open(path, "w") as f: - f.write(response.data) + :return string: quoted value + """ + if type(obj) == list: + return ','.join(obj) + else: + return str(obj) - return path + def sanitize_for_serialization(self, obj): + """ + Sanitize an object for Request. - def __deserialize_primitive(self, data, klass): - """ - Deserialize string to primitive type + If obj is None, return None. + If obj is str, int, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is list, santize each element in the list. + If obj is dict, return the dict. + If obj is swagger model, return the properties dict. + """ + if isinstance(obj, type(None)): + return None + elif isinstance(obj, (str, int, float, bool, tuple)): + return obj + elif isinstance(obj, list): + return [self.sanitize_for_serialization(sub_obj) + for sub_obj in obj] + elif isinstance(obj, (datetime, date)): + return obj.isoformat() + else: + if isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `swagger_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = {obj.attribute_map[key[1:]]: val + for key, val in iteritems(obj.__dict__) + if key != 'swagger_types' + and key != 'attribute_map' + and val is not None} - :param data: str - :param klass: class literal + return {key: self.sanitize_for_serialization(val) + for key, val in iteritems(obj_dict)} - :return: int, float, str, bool - """ - try: - value = klass(data) - except UnicodeEncodeError: - value = unicode(data) - except TypeError: - value = data - return value + def deserialize(self, response, response_type): + """ + Derialize response into an object. - def __deserialize_object(self): - """ - Deserialize empty object - """ - return object() + :param response: RESTResponse object to be deserialized + :param response_type: class literal for + deserialzied object, or string of class name - def __deserialize_date(self, string): - """ - Deserialize string to date + :return: deserialized object + """ + # handle file downloading + # save response body into a tmp file and return the instance + if "file" == response_type: + return self.__deserialize_file(response) - :param string: str - :return: date - """ - try: - from dateutil.parser import parse - return parse(string).date() - except ImportError: - return string - except ValueError: - raise ApiException(status=0, reason="Failed to parse `{0}` into a date object".format(string)) - - def __deserialize_datatime(self, string): - """ - Deserialize string to datetime. + # fetch data from response object + try: + data = json.loads(response.data) + except ValueError: + data = response.data - The string should be in iso8601 datetime format. + return self.__deserialize(data, response_type) - :param string: str - :return: datetime - """ - try: - from dateutil.parser import parse - return parse(string) - except ImportError: - return string - except ValueError: - raise ApiException(status=0, reason="Failed to parse `{0}` into a datetime object".format(string)) + def __deserialize(self, data, klass): + """ + :param data: dict, list or str + :param klass: class literal, or string of class name - def __deserialize_model(self, data, klass): - """ - Deserialize list or dict to model + :return: object + """ + if data is None: + return None - :param data: dict, list - :param klass: class literal - """ - instance = klass() + if type(klass) == str: + if 'list[' in klass: + sub_kls = re.match('list\[(.*)\]', klass).group(1) + return [self.__deserialize(sub_data, sub_kls) + for sub_data in data] - for attr, attr_type in iteritems(instance.swagger_types): - if data is not None \ - and instance.attribute_map[attr] in data\ - and isinstance(data, (list, dict)): - value = data[instance.attribute_map[attr]] - setattr(instance, attr, self.__deserialize(value, attr_type)) + if 'dict(' in klass: + sub_kls = re.match('dict\((.*), (.*)\)', klass).group(2) + return {k: self.__deserialize(v, sub_kls) + for k, v in iteritems(data)} - return instance + # convert str to class + # for native types + if klass in ['int', 'float', 'str', 'bool', + "date", 'datetime', "object"]: + klass = eval(klass) + # for model types + else: + klass = eval('models.' + klass) + + if klass in [int, float, str, bool]: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object() + elif klass == date: + return self.__deserialize_date(data) + elif klass == datetime: + return self.__deserialize_datatime(data) + else: + return self.__deserialize_model(data, klass) + + def call_api(self, resource_path, method, + path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, + response_type=None, auth_settings=None, callback=None): + """ + Perform http request and return deserialized data + + + :param resource_path: Path to method endpoint. + :param method: Method to call. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param response: Response data type. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param callback function: Callback function for asynchronous request. + If provide this parameter, + the request will be called asynchronously. + :return: + If provide parameter callback, + the request will be called asynchronously. + The method will return the request thread. + If parameter callback is None, + then the method will return the response directly. + """ + if callback is None: + return self.__call_api(resource_path, method, + path_params, query_params, header_params, + body, post_params, files, + response_type, auth_settings, callback) + else: + thread = threading.Thread(target=self.__call_api, + args=(resource_path, method, + path_params, query_params, + header_params, body, + post_params, files, + response_type, auth_settings, + callback)) + thread.start() + return thread + + def request(self, method, url, query_params=None, headers=None, + post_params=None, body=None): + """ + Perform http request using RESTClient. + """ + if method == "GET": + return RESTClient.GET(url, + query_params=query_params, + headers=headers) + elif method == "HEAD": + return RESTClient.HEAD(url, + query_params=query_params, + headers=headers) + elif method == "POST": + return RESTClient.POST(url, + headers=headers, + post_params=post_params, + body=body) + elif method == "PUT": + return RESTClient.PUT(url, + headers=headers, + post_params=post_params, + body=body) + elif method == "PATCH": + return RESTClient.PATCH(url, + headers=headers, + post_params=post_params, + body=body) + elif method == "DELETE": + return RESTClient.DELETE(url, + query_params=query_params, + headers=headers) + else: + raise ValueError( + "http method must be `GET`, `HEAD`," + " `POST`, `PATCH`, `PUT` or `DELETE`." + ) + + def prepare_post_parameters(self, post_params=None, files=None): + params = {} + + if post_params: + params.update(post_params) + + if files: + for k, v in iteritems(files): + if not v: + continue + + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = mimetypes.\ + guess_type(filename)[0] or 'application/octet-stream' + params[k] = tuple([filename, filedata, mimetype]) + + return params + + def select_header_accept(self, accepts): + """ + Return `Accept` based on an array of accepts provided + """ + if not accepts: + return + + accepts = list(map(lambda x: x.lower(), accepts)) + + if 'application/json' in accepts: + return 'application/json' + else: + return ', '.join(accepts) + + def select_header_content_type(self, content_types): + """ + Return `Content-Type` baseed on an array of content_types provided + """ + if not content_types: + return 'application/json' + + content_types = list(map(lambda x: x.lower(), content_types)) + + if 'application/json' in content_types: + return 'application/json' + else: + return content_types[0] + + def update_params_for_auth(self, headers, querys, auth_settings): + """ + Update header and query params based on authentication setting + """ + config = Configuration() + + if not auth_settings: + return + + for auth in auth_settings: + auth_setting = config.auth_settings().get(auth) + if auth_setting: + if auth_setting['in'] == 'header': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + querys[auth_setting['key']] = auth_setting['value'] + else: + raise ValueError( + 'Authentication token must be in `query` or `header`' + ) + + def __deserialize_file(self, response): + """ + Save response body into a file in (the defined) temporary folder, + using the filename from the `Content-Disposition` header if provided, + otherwise a random filename. + + :param response: RESTResponse + :return: file path + """ + config = Configuration() + + fd, path = tempfile.mkstemp(dir=config.temp_folder_path) + os.close(fd) + os.remove(path) + + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + filename = re.\ + search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).\ + group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "w") as f: + f.write(response.data) + + return path + + def __deserialize_primitive(self, data, klass): + """ + Deserialize string to primitive type + + :param data: str + :param klass: class literal + + :return: int, float, str, bool + """ + try: + value = klass(data) + except UnicodeEncodeError: + value = unicode(data) + except TypeError: + value = data + return value + + def __deserialize_object(self): + """ + Deserialize empty object + """ + return object() + + def __deserialize_date(self, string): + """ + Deserialize string to date + + :param string: str + :return: date + """ + try: + from dateutil.parser import parse + return parse(string).date() + except ImportError: + return string + except ValueError: + raise ApiException( + status=0, + reason="Failed to parse `{0}` into a date object" + .format(string) + ) + + def __deserialize_datatime(self, string): + """ + Deserialize string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str + :return: datetime + """ + try: + from dateutil.parser import parse + return parse(string) + except ImportError: + return string + except ValueError: + raise ApiException( + status=0, + reason="Failed to parse `{0}` into a datetime object". + format(string) + ) + + def __deserialize_model(self, data, klass): + """ + Deserialize list or dict to model + + :param data: dict, list + :param klass: class literal + """ + instance = klass() + + for attr, attr_type in iteritems(instance.swagger_types): + if data is not None \ + and instance.attribute_map[attr] in data\ + and isinstance(data, (list, dict)): + value = data[instance.attribute_map[attr]] + setattr(instance, attr, self.__deserialize(value, attr_type)) + + return instance diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index 0feb7af5d59..bf26ab362b1 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -5,6 +5,7 @@ import httplib import sys import logging + def singleton(cls, *args, **kw): instances = {} @@ -23,6 +24,8 @@ class Configuration(object): self.host = "{{basePath}}" # Default api client self.api_client = None + # Temp file folder + self.temp_folder_path = None # Authentication Settings self.api_key = {} self.api_key_prefix = {} @@ -93,29 +96,33 @@ class Configuration(object): def auth_settings(self): """ Return Auth Settings for api client """ - return { {{#authMethods}}{{#isApiKey}} - '{{name}}': { - 'type': 'api_key', - 'in': {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}, - 'key': '{{keyParamName}}', - 'value': self.get_api_key_with_prefix('{{keyParamName}}') - }, - {{/isApiKey}}{{#isBasic}} - '{{name}}': { - 'type': 'basic', - 'in': 'header', - 'key': 'Authorization', - 'value': self.get_basic_auth_token() - }, - {{/isBasic}}{{/authMethods}} - } + return { +{{#authMethods}} +{{#isApiKey}} + '{{name}}': + { + 'type': 'api_key', + 'in': {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}, + 'key': '{{keyParamName}}', + 'value': self.get_api_key_with_prefix('{{keyParamName}}') + }, +{{/isApiKey}} +{{#isBasic}} + '{{name}}': + { + 'type': 'basic', + 'in': 'header', + 'key': 'Authorization', + 'value': self.get_basic_auth_token() + }, +{{/isBasic}} +{{/authMethods}} + } def to_debug_report(self): return "Python SDK Debug Report:\n"\ "OS: {env}\n"\ "Python Version: {pyversion}\n"\ "Version of the API: {{version}}\n"\ - "SDK Package Version: {{packageVersion}}".format(env=sys.platform, pyversion=sys.version) - - - + "SDK Package Version: {{packageVersion}}".\ + format(env=sys.platform, pyversion=sys.version) diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 3dda53963a3..2394cd955f3 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -19,18 +19,20 @@ Copyright 2015 SmartBear Software {{#models}} {{#model}} + class {{classname}}(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): """ Swagger model - :param dict swaggerTypes: The key is attribute name and the value is attribute type. - :param dict attributeMap: The key is attribute name and the value is json key in definition. + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. """ self.swagger_types = { {{#vars}}'{{name}}': '{{{datatype}}}'{{#hasMore}}, @@ -41,11 +43,12 @@ class {{classname}}(object): {{#vars}}'{{name}}': '{{baseName}}'{{#hasMore}}, {{/hasMore}}{{/vars}} } - {{#vars}} - {{#description}}# {{description}}{{/description}} - self._{{name}} = None # {{{datatype}}} - {{/vars}} - {{#vars}} + +{{#vars}} + self._{{name}} = None{{#description}} # {{description}}{{/description}} +{{/vars}} + +{{#vars}} @property def {{name}}(self): return self._{{name}} @@ -54,18 +57,21 @@ class {{classname}}(object): def {{name}}(self, {{name}}): {{#isEnum}}allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] if {{name}} not in allowed_values: - raise ValueError("Invalid value for `{{name}}`, must be one of {0}".format(allowed_values)) - {{/isEnum}} - self._{{name}} = {{name}} - {{/vars}} + raise ValueError( + "Invalid value for `{{name}}`, must be one of {0}" + .format(allowed_values) + ) + {{/isEnum}}self._{{name}} = {{name}} + +{{/vars}} def __repr__(self): properties = [] for p in self.__dict__: if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) + properties.append('{prop}={val!r}' + .format(prop=p, val=self.__dict__[p])) - return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) + return '<{name} {props}>'.format(name=__name__, + props=' '.join(properties)) {{/model}} {{/models}} - - diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 7cf08f50429..fab813a4cc9 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -51,6 +51,7 @@ class RESTResponse(io.IOBase): """ return self.urllib3_response.getheader(name, default) + class RESTClientObject(object): def __init__(self, pools_size=4): @@ -87,14 +88,17 @@ class RESTClientObject(object): :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` - :param post_params: request post parameters, `application/x-www-form-urlencode` + :param post_params: request post parameters, + `application/x-www-form-urlencode` and `multipart/form-data` """ method = method.upper() assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH'] if post_params and body: - raise ValueError("body parameter cannot be used with post_params parameter.") + raise ValueError( + "body parameter cannot be used with post_params parameter." + ) post_params = post_params or {} headers = headers or {} @@ -144,22 +148,37 @@ class RESTClientObject(object): return r def GET(self, url, headers=None, query_params=None): - return self.request("GET", url, headers=headers, query_params=query_params) + return self.request("GET", url, + headers=headers, + query_params=query_params) def HEAD(self, url, headers=None, query_params=None): - return self.request("HEAD", url, headers=headers, query_params=query_params) + return self.request("HEAD", url, + headers=headers, + query_params=query_params) def DELETE(self, url, headers=None, query_params=None): - return self.request("DELETE", url, headers=headers, query_params=query_params) + return self.request("DELETE", url, + headers=headers, + query_params=query_params) def POST(self, url, headers=None, post_params=None, body=None): - return self.request("POST", url, headers=headers, post_params=post_params, body=body) + return self.request("POST", url, + headers=headers, + post_params=post_params, + body=body) def PUT(self, url, headers=None, post_params=None, body=None): - return self.request("PUT", url, headers=headers, post_params=post_params, body=body) + return self.request("PUT", url, + headers=headers, + post_params=post_params, + body=body) def PATCH(self, url, headers=None, post_params=None, body=None): - return self.request("PATCH", url, headers=headers, post_params=post_params, body=body) + return self.request("PATCH", url, + headers=headers, + post_params=post_params, + body=body) class ApiException(Exception): @@ -190,6 +209,7 @@ class ApiException(Exception): return error_message + class RESTClient(object): """ A class with all class methods to perform JSON requests. diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/swagger_client/api_client.py index 4ee306581ba..37bf1be69c0 100644 --- a/samples/client/petstore/python/swagger_client/api_client.py +++ b/samples/client/petstore/python/swagger_client/api_client.py @@ -27,415 +27,480 @@ from datetime import date from six import iteritems try: - # for python3 - from urllib.parse import quote + # for python3 + from urllib.parse import quote except ImportError: - # for python2 - from urllib import quote + # for python2 + from urllib import quote from .configuration import Configuration + class ApiClient(object): - """ - Generic API client for Swagger client library builds - - :param host: The base path for the server to call - :param header_name: a header to pass when making calls to the API - :param header_value: a header value to pass when making calls to the API - """ - def __init__(self, host=Configuration().host, header_name=None, header_value=None): - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.host = host - self.cookie = None - # Set default User-Agent. - self.user_agent = 'Python-Swagger' - - @property - def user_agent(self): - return self.default_headers['User-Agent'] - - @user_agent.setter - def user_agent(self, value): - self.default_headers['User-Agent'] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - def __call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None): - - # headers parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params['Cookie'] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - for k, v in iteritems(path_params): - replacement = quote(str(self.to_path_value(v))) - resource_path = resource_path.replace('{' + k + '}', replacement) - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = {k: self.to_path_value(v) for k, v in iteritems(query_params)} - - # post parameters - if post_params: - post_params = self.prepare_post_parameters(post_params, files) - post_params = self.sanitize_for_serialization(post_params) - - # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # request url - url = self.host + resource_path - - # perform request and return response - response_data = self.request(method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body) - - self.last_response = response_data - - # deserialize response data - if response_type: - deserialized_data = self.deserialize(response_data, response_type) - else: - deserialized_data = None - - if callback: - callback(deserialized_data) - else: - return deserialized_data - - def to_path_value(self, obj): """ - Convert a string or object to a path-friendly value + Generic API client for Swagger client library builds - :param obj: object or string value - - :return string: quoted value + :param host: The base path for the server to call + :param header_name: a header to pass when making calls to the API + :param header_value: a header value to pass when making calls to the API """ - if type(obj) == list: - return ','.join(obj) - else: - return str(obj) + def __init__(self, host=Configuration().host, + header_name=None, header_value=None): - def sanitize_for_serialization(self, obj): - """ - Sanitize an object for Request. + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value + self.host = host + self.cookie = None + # Set default User-Agent. + self.user_agent = 'Python-Swagger' - If obj is None, return None. - If obj is str, int, float, bool, return directly. - If obj is datetime.datetime, datetime.date convert to string in iso8601 format. - If obj is list, santize each element in the list. - If obj is dict, return the dict. - If obj is swagger model, return the properties dict. - """ - if isinstance(obj, type(None)): - return None - elif isinstance(obj, (str, int, float, bool, tuple)): - return obj - elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] - elif isinstance(obj, (datetime, date)): - return obj.isoformat() - else: - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in model definition for request. - obj_dict = {obj.attribute_map[key[1:]]: val - for key, val in iteritems(obj.__dict__) - if key != 'swagger_types' and key != 'attribute_map' and val is not None} - return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} + @property + def user_agent(self): + return self.default_headers['User-Agent'] - def deserialize(self, response, response_type): - """ - Derialize response into an object. + @user_agent.setter + def user_agent(self, value): + self.default_headers['User-Agent'] = value - :param response: RESTResponse object to be deserialized - :param response_type: class literal for deserialzied object, or string of class name + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value - :return: deserialized object - """ - # handle file downloading - save response body into a tmp file and return the instance - if "file" == response_type: - return self.__deserialize_file(response) + def __call_api(self, resource_path, method, + path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, + response_type=None, auth_settings=None, callback=None): - # fetch data from response object - try: - data = json.loads(response.data) - except ValueError: - data = response.data + # headers parameters + header_params = header_params or {} + header_params.update(self.default_headers) + if self.cookie: + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) - return self.__deserialize(data, response_type) + # path parameters + if path_params: + path_params = self.sanitize_for_serialization(path_params) + for k, v in iteritems(path_params): + replacement = quote(str(self.to_path_value(v))) + resource_path = resource_path.\ + replace('{' + k + '}', replacement) - def __deserialize(self, data, klass): - """ - :param data: dict, list or str - :param klass: class literal, or string of class name + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + query_params = {k: self.to_path_value(v) + for k, v in iteritems(query_params)} - :return: object - """ - if data is None: - return None + # post parameters + if post_params: + post_params = self.prepare_post_parameters(post_params, files) + post_params = self.sanitize_for_serialization(post_params) - if type(klass) == str: - if 'list[' in klass: - sub_kls = re.match('list\[(.*)\]', klass).group(1) - return [self.__deserialize(sub_data, sub_kls) for sub_data in data] + # auth setting + self.update_params_for_auth(header_params, query_params, auth_settings) - if 'dict(' in klass: - sub_kls = re.match('dict\((.*), (.*)\)', klass).group(2) - return {k: self.__deserialize(v, sub_kls) for k, v in iteritems(data)} + # body + if body: + body = self.sanitize_for_serialization(body) - # convert str to class - # for native types - if klass in ['int', 'float', 'str', 'bool', "date", 'datetime', "object"]: - klass = eval(klass) - # for model types - else: - klass = eval('models.' + klass) + # request url + url = self.host + resource_path - if klass in [int, float, str, bool]: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object() - elif klass == date: - return self.__deserialize_date(data) - elif klass == datetime: - return self.__deserialize_datatime(data) - else: - return self.__deserialize_model(data, klass) + # perform request and return response + response_data = self.request(method, url, + query_params=query_params, + headers=header_params, + post_params=post_params, body=body) - def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_type=None, auth_settings=None, callback=None): - """ - Perform http request and return deserialized data + self.last_response = response_data - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, for `multipart/form-data`. - :param callback function: Callback function for asynchronous request. - If provide this parameter, the request will be called asynchronously. - :return: - If provide parameter callback, the request will be called asynchronously. - The method will return the request thread. - If parameter callback is None, then the method will return the response directly. - """ - if callback is None: - return self.__call_api(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_type, auth_settings, callback) - else: - thread = threading.Thread(target=self.__call_api, - args=(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_type, auth_settings, callback)) - thread.start() - return thread - - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None): - """ - Perform http request using RESTClient. - """ - if method == "GET": - return RESTClient.GET(url, query_params=query_params, headers=headers) - elif method == "HEAD": - return RESTClient.HEAD(url, query_params=query_params, headers=headers) - elif method == "POST": - return RESTClient.POST(url, headers=headers, post_params=post_params, body=body) - elif method == "PUT": - return RESTClient.PUT(url, headers=headers, post_params=post_params, body=body) - elif method == "PATCH": - return RESTClient.PATCH(url, headers=headers, post_params=post_params, body=body) - elif method == "DELETE": - return RESTClient.DELETE(url, query_params=query_params, headers=headers) - else: - raise ValueError("http method must be `GET`, `HEAD`, `POST`, `PATCH`, `PUT` or `DELETE`") - - def prepare_post_parameters(self, post_params=None, files=None): - params = {} - - if post_params: - params.update(post_params) - - if files: - for k, v in iteritems(files): - if v: - with open(v, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' - params[k] = tuple([filename, filedata, mimetype]) - - return params - - def select_header_accept(self, accepts): - """ - Return `Accept` based on an array of accepts provided - """ - if not accepts: - return - - accepts = list(map(lambda x: x.lower(), accepts)) - - if 'application/json' in accepts: - return 'application/json' - else: - return ', '.join(accepts) - - def select_header_content_type(self, content_types): - """ - Return `Content-Type` baseed on an array of content_types provided - """ - if not content_types: - return 'application/json' - - content_types = list(map(lambda x: x.lower(), content_types)) - - if 'application/json' in content_types: - return 'application/json' - else: - return content_types[0] - - def update_params_for_auth(self, headers, querys, auth_settings): - """ - Update header and query params based on authentication setting - """ - config = Configuration() - - if not auth_settings: - return - - for auth in auth_settings: - auth_setting = config.auth_settings().get(auth) - if auth_setting: - if auth_setting['in'] == 'header': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - querys[auth_setting['key']] = auth_setting['value'] + # deserialize response data + if response_type: + deserialized_data = self.deserialize(response_data, response_type) else: - raise ValueError('Authentication token must be in `query` or `header`') + deserialized_data = None - def __deserialize_file(self, response): - """ - Save response body into a file in (the defined) temporary folder, using the filename - from the `Content-Disposition` header if provided, otherwise a random filename. + if callback: + callback(deserialized_data) + else: + return deserialized_data - :param response: RESTResponse - :return: file path - """ - fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path) - os.close(fd) - os.remove(path) + def to_path_value(self, obj): + """ + Convert a string or object to a path-friendly value - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).group(1) - path = os.path.join(os.path.dirname(path), filename) + :param obj: object or string value - with open(path, "w") as f: - f.write(response.data) + :return string: quoted value + """ + if type(obj) == list: + return ','.join(obj) + else: + return str(obj) - return path + def sanitize_for_serialization(self, obj): + """ + Sanitize an object for Request. - def __deserialize_primitive(self, data, klass): - """ - Deserialize string to primitive type + If obj is None, return None. + If obj is str, int, float, bool, return directly. + If obj is datetime.datetime, datetime.date + convert to string in iso8601 format. + If obj is list, santize each element in the list. + If obj is dict, return the dict. + If obj is swagger model, return the properties dict. + """ + if isinstance(obj, type(None)): + return None + elif isinstance(obj, (str, int, float, bool, tuple)): + return obj + elif isinstance(obj, list): + return [self.sanitize_for_serialization(sub_obj) + for sub_obj in obj] + elif isinstance(obj, (datetime, date)): + return obj.isoformat() + else: + if isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `swagger_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = {obj.attribute_map[key[1:]]: val + for key, val in iteritems(obj.__dict__) + if key != 'swagger_types' + and key != 'attribute_map' + and val is not None} - :param data: str - :param klass: class literal + return {key: self.sanitize_for_serialization(val) + for key, val in iteritems(obj_dict)} - :return: int, float, str, bool - """ - try: - value = klass(data) - except UnicodeEncodeError: - value = unicode(data) - except TypeError: - value = data - return value + def deserialize(self, response, response_type): + """ + Derialize response into an object. - def __deserialize_object(self): - """ - Deserialize empty object - """ - return object() + :param response: RESTResponse object to be deserialized + :param response_type: class literal for + deserialzied object, or string of class name - def __deserialize_date(self, string): - """ - Deserialize string to date + :return: deserialized object + """ + # handle file downloading + # save response body into a tmp file and return the instance + if "file" == response_type: + return self.__deserialize_file(response) - :param string: str - :return: date - """ - try: - from dateutil.parser import parse - return parse(string).date() - except ImportError: - return string - except ValueError: - raise ApiException(status=0, reason="Failed to parse `{0}` into a date object".format(string)) - - def __deserialize_datatime(self, string): - """ - Deserialize string to datetime. + # fetch data from response object + try: + data = json.loads(response.data) + except ValueError: + data = response.data - The string should be in iso8601 datetime format. + return self.__deserialize(data, response_type) - :param string: str - :return: datetime - """ - try: - from dateutil.parser import parse - return parse(string) - except ImportError: - return string - except ValueError: - raise ApiException(status=0, reason="Failed to parse `{0}` into a datetime object".format(string)) + def __deserialize(self, data, klass): + """ + :param data: dict, list or str + :param klass: class literal, or string of class name - def __deserialize_model(self, data, klass): - """ - Deserialize list or dict to model + :return: object + """ + if data is None: + return None - :param data: dict, list - :param klass: class literal - """ - instance = klass() + if type(klass) == str: + if 'list[' in klass: + sub_kls = re.match('list\[(.*)\]', klass).group(1) + return [self.__deserialize(sub_data, sub_kls) + for sub_data in data] - for attr, attr_type in iteritems(instance.swagger_types): - if data is not None \ - and instance.attribute_map[attr] in data\ - and isinstance(data, (list, dict)): - value = data[instance.attribute_map[attr]] - setattr(instance, attr, self.__deserialize(value, attr_type)) + if 'dict(' in klass: + sub_kls = re.match('dict\((.*), (.*)\)', klass).group(2) + return {k: self.__deserialize(v, sub_kls) + for k, v in iteritems(data)} - return instance + # convert str to class + # for native types + if klass in ['int', 'float', 'str', 'bool', + "date", 'datetime', "object"]: + klass = eval(klass) + # for model types + else: + klass = eval('models.' + klass) + + if klass in [int, float, str, bool]: + return self.__deserialize_primitive(data, klass) + elif klass == object: + return self.__deserialize_object() + elif klass == date: + return self.__deserialize_date(data) + elif klass == datetime: + return self.__deserialize_datatime(data) + else: + return self.__deserialize_model(data, klass) + + def call_api(self, resource_path, method, + path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, + response_type=None, auth_settings=None, callback=None): + """ + Perform http request and return deserialized data + + + :param resource_path: Path to method endpoint. + :param method: Method to call. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param response: Response data type. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param callback function: Callback function for asynchronous request. + If provide this parameter, + the request will be called asynchronously. + :return: + If provide parameter callback, + the request will be called asynchronously. + The method will return the request thread. + If parameter callback is None, + then the method will return the response directly. + """ + if callback is None: + return self.__call_api(resource_path, method, + path_params, query_params, header_params, + body, post_params, files, + response_type, auth_settings, callback) + else: + thread = threading.Thread(target=self.__call_api, + args=(resource_path, method, + path_params, query_params, + header_params, body, + post_params, files, + response_type, auth_settings, + callback)) + thread.start() + return thread + + def request(self, method, url, query_params=None, headers=None, + post_params=None, body=None): + """ + Perform http request using RESTClient. + """ + if method == "GET": + return RESTClient.GET(url, + query_params=query_params, + headers=headers) + elif method == "HEAD": + return RESTClient.HEAD(url, + query_params=query_params, + headers=headers) + elif method == "POST": + return RESTClient.POST(url, + headers=headers, + post_params=post_params, + body=body) + elif method == "PUT": + return RESTClient.PUT(url, + headers=headers, + post_params=post_params, + body=body) + elif method == "PATCH": + return RESTClient.PATCH(url, + headers=headers, + post_params=post_params, + body=body) + elif method == "DELETE": + return RESTClient.DELETE(url, + query_params=query_params, + headers=headers) + else: + raise ValueError( + "http method must be `GET`, `HEAD`," + " `POST`, `PATCH`, `PUT` or `DELETE`." + ) + + def prepare_post_parameters(self, post_params=None, files=None): + params = {} + + if post_params: + params.update(post_params) + + if files: + for k, v in iteritems(files): + if not v: + continue + + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = mimetypes.\ + guess_type(filename)[0] or 'application/octet-stream' + params[k] = tuple([filename, filedata, mimetype]) + + return params + + def select_header_accept(self, accepts): + """ + Return `Accept` based on an array of accepts provided + """ + if not accepts: + return + + accepts = list(map(lambda x: x.lower(), accepts)) + + if 'application/json' in accepts: + return 'application/json' + else: + return ', '.join(accepts) + + def select_header_content_type(self, content_types): + """ + Return `Content-Type` baseed on an array of content_types provided + """ + if not content_types: + return 'application/json' + + content_types = list(map(lambda x: x.lower(), content_types)) + + if 'application/json' in content_types: + return 'application/json' + else: + return content_types[0] + + def update_params_for_auth(self, headers, querys, auth_settings): + """ + Update header and query params based on authentication setting + """ + config = Configuration() + + if not auth_settings: + return + + for auth in auth_settings: + auth_setting = config.auth_settings().get(auth) + if auth_setting: + if auth_setting['in'] == 'header': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + querys[auth_setting['key']] = auth_setting['value'] + else: + raise ValueError( + 'Authentication token must be in `query` or `header`' + ) + + def __deserialize_file(self, response): + """ + Save response body into a file in (the defined) temporary folder, + using the filename from the `Content-Disposition` header if provided, + otherwise a random filename. + + :param response: RESTResponse + :return: file path + """ + config = Configuration() + + fd, path = tempfile.mkstemp(dir=config.temp_folder_path) + os.close(fd) + os.remove(path) + + content_disposition = response.getheader("Content-Disposition") + if content_disposition: + filename = re.\ + search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).\ + group(1) + path = os.path.join(os.path.dirname(path), filename) + + with open(path, "w") as f: + f.write(response.data) + + return path + + def __deserialize_primitive(self, data, klass): + """ + Deserialize string to primitive type + + :param data: str + :param klass: class literal + + :return: int, float, str, bool + """ + try: + value = klass(data) + except UnicodeEncodeError: + value = unicode(data) + except TypeError: + value = data + return value + + def __deserialize_object(self): + """ + Deserialize empty object + """ + return object() + + def __deserialize_date(self, string): + """ + Deserialize string to date + + :param string: str + :return: date + """ + try: + from dateutil.parser import parse + return parse(string).date() + except ImportError: + return string + except ValueError: + raise ApiException( + status=0, + reason="Failed to parse `{0}` into a date object" + .format(string) + ) + + def __deserialize_datatime(self, string): + """ + Deserialize string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str + :return: datetime + """ + try: + from dateutil.parser import parse + return parse(string) + except ImportError: + return string + except ValueError: + raise ApiException( + status=0, + reason="Failed to parse `{0}` into a datetime object". + format(string) + ) + + def __deserialize_model(self, data, klass): + """ + Deserialize list or dict to model + + :param data: dict, list + :param klass: class literal + """ + instance = klass() + + for attr, attr_type in iteritems(instance.swagger_types): + if data is not None \ + and instance.attribute_map[attr] in data\ + and isinstance(data, (list, dict)): + value = data[instance.attribute_map[attr]] + setattr(instance, attr, self.__deserialize(value, attr_type)) + + return instance diff --git a/samples/client/petstore/python/swagger_client/apis/__init__.py b/samples/client/petstore/python/swagger_client/apis/__init__.py index 128b25dad82..592a56e282d 100644 --- a/samples/client/petstore/python/swagger_client/apis/__init__.py +++ b/samples/client/petstore/python/swagger_client/apis/__init__.py @@ -4,4 +4,3 @@ from __future__ import absolute_import from .user_api import UserApi from .pet_api import PetApi from .store_api import StoreApi - diff --git a/samples/client/petstore/python/swagger_client/apis/pet_api.py b/samples/client/petstore/python/swagger_client/apis/pet_api.py index 4865352b7cd..ad70dac30b3 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -17,7 +17,8 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ from __future__ import absolute_import @@ -30,6 +31,7 @@ from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient + class PetApi(object): def __init__(self, api_client=None): @@ -40,34 +42,38 @@ class PetApi(object): if not config.api_client: config.api_client = ApiClient('http://petstore.swagger.io/v2') self.api_client = config.api_client - - + def update_pet(self, **kwargs): """ Update an existing pet - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.update_pet(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param Pet body: Pet object that needs to be added to the store - :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['body'] 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 update_pet" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method update_pet" % key + ) params[key] = val del params['kwargs'] @@ -75,61 +81,74 @@ class PetApi(object): method = 'PUT' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - if 'body' in params: body_params = params['body'] - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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(['application/json', 'application/xml']) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type(['application/json', 'application/xml']) # Authentication setting auth_settings = ['petstore_auth'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def add_pet(self, **kwargs): """ Add a new pet to the store - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.add_pet(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param Pet body: Pet object that needs to be added to the store - :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['body'] 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 add_pet" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method add_pet" % key + ) params[key] = val del params['kwargs'] @@ -137,61 +156,74 @@ class PetApi(object): method = 'POST' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - if 'body' in params: body_params = params['body'] - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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(['application/json', 'application/xml']) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type(['application/json', 'application/xml']) # Authentication setting auth_settings = ['petstore_auth'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def find_pets_by_status(self, **kwargs): """ Finds Pets by status Multiple status values can be provided with comma seperated strings - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.find_pets_by_status(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param list[str] status: Status values that need to be considered for filter - :return: list[Pet] - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['status'] 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 find_pets_by_status" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method find_pets_by_status" % key + ) params[key] = val del params['kwargs'] @@ -199,61 +231,74 @@ class PetApi(object): method = 'GET' path_params = {} - + query_params = {} - if 'status' in params: query_params['status'] = params['status'] - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = ['petstore_auth'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='list[Pet]', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='list[Pet]', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def find_pets_by_tags(self, **kwargs): """ Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.find_pets_by_tags(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param list[str] tags: Tags to filter by - :return: list[Pet] - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['tags'] 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 find_pets_by_tags" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method find_pets_by_tags" % key + ) params[key] = val del params['kwargs'] @@ -261,64 +306,77 @@ class PetApi(object): method = 'GET' path_params = {} - + query_params = {} - if 'tags' in params: query_params['tags'] = params['tags'] - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = ['petstore_auth'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='list[Pet]', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='list[Pet]', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def get_pet_by_id(self, pet_id, **kwargs): """ Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_pet_by_id(pet_id, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param int pet_id: ID of pet that needs to be fetched (required) - :return: Pet - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ # verify the required parameter 'pet_id' is set if pet_id is None: raise ValueError("Missing the required parameter `pet_id` when calling `get_pet_by_id`") - + 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" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method get_pet_by_id" % key + ) params[key] = val del params['kwargs'] @@ -326,66 +384,79 @@ class PetApi(object): method = 'GET' path_params = {} - if 'pet_id' in params: - path_params['petId'] = params['pet_id'] - + path_params['petId'] = params['pet_id'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + 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, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='Pet', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='Pet', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def update_pet_with_form(self, pet_id, **kwargs): """ Updates a pet in the store with form data - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.update_pet_with_form(pet_id, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param str pet_id: ID of pet that needs to be updated (required) :param str name: Updated name of the pet :param str status: Updated status of the pet - :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ # verify the required parameter 'pet_id' is set if pet_id is None: raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`") - + all_params = ['pet_id', 'name', 'status'] 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 update_pet_with_form" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method update_pet_with_form" % key + ) params[key] = val del params['kwargs'] @@ -393,71 +464,82 @@ class PetApi(object): method = 'POST' path_params = {} - if 'pet_id' in params: - path_params['petId'] = params['pet_id'] - + path_params['petId'] = params['pet_id'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - if 'name' in params: form_params['name'] = params['name'] - if 'status' in params: form_params['status'] = params['status'] - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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(['application/x-www-form-urlencoded']) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type(['application/x-www-form-urlencoded']) # Authentication setting auth_settings = ['petstore_auth'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def delete_pet(self, pet_id, **kwargs): """ Deletes a pet - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.delete_pet(pet_id, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param int pet_id: Pet id to delete (required) :param str api_key: - :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ # verify the required parameter 'pet_id' is set if pet_id is None: raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") - + all_params = ['pet_id', 'api_key'] 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 delete_pet" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method delete_pet" % key + ) params[key] = val del params['kwargs'] @@ -465,69 +547,81 @@ class PetApi(object): method = 'DELETE' path_params = {} - if 'pet_id' in params: - path_params['petId'] = params['pet_id'] - + path_params['petId'] = params['pet_id'] + query_params = {} - + header_params = {} - if 'api_key' in params: header_params['api_key'] = params['api_key'] - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = ['petstore_auth'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def upload_file(self, pet_id, **kwargs): """ uploads an image - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.upload_file(pet_id, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param int pet_id: ID of pet to update (required) :param str additional_metadata: Additional data to pass to server :param file file: file to upload - :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ # verify the required parameter 'pet_id' is set if pet_id is None: raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") - + all_params = ['pet_id', 'additional_metadata', 'file'] 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 upload_file" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method upload_file" % key + ) params[key] = val del params['kwargs'] @@ -535,38 +629,43 @@ class PetApi(object): method = 'POST' path_params = {} - if 'pet_id' in params: - path_params['petId'] = params['pet_id'] - + path_params['petId'] = params['pet_id'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - if 'additional_metadata' in params: form_params['additionalMetadata'] = params['additional_metadata'] - if 'file' in params: files['file'] = params['file'] - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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(['multipart/form-data']) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type(['multipart/form-data']) # Authentication setting auth_settings = ['petstore_auth'] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - diff --git a/samples/client/petstore/python/swagger_client/apis/store_api.py b/samples/client/petstore/python/swagger_client/apis/store_api.py index f60d2de77de..589362cdddd 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/swagger_client/apis/store_api.py @@ -17,7 +17,8 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ from __future__ import absolute_import @@ -30,6 +31,7 @@ from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient + class StoreApi(object): def __init__(self, api_client=None): @@ -40,33 +42,37 @@ class StoreApi(object): if not config.api_client: config.api_client = ApiClient('http://petstore.swagger.io/v2') self.api_client = config.api_client - - + def get_inventory(self, **kwargs): """ Returns pet inventories by status Returns a map of status codes to quantities - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_inventory(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) - + :param callback function: The callback function + for asynchronous request. (optional) :return: dict(str, int) - If the method is called asynchronously, returns the request thread. + 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" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method get_inventory" % key + ) params[key] = val del params['kwargs'] @@ -74,58 +80,72 @@ class StoreApi(object): method = 'GET' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + 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, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='dict(str, int)', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='dict(str, int)', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def place_order(self, **kwargs): """ Place an order for a pet - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.place_order(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param Order body: order placed for purchasing the pet - :return: Order - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['body'] 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 place_order" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method place_order" % key + ) params[key] = val del params['kwargs'] @@ -133,64 +153,77 @@ class StoreApi(object): method = 'POST' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - if 'body' in params: body_params = params['body'] - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='Order', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='Order', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def get_order_by_id(self, order_id, **kwargs): """ Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_order_by_id(order_id, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param str order_id: ID of pet that needs to be fetched (required) - :return: Order - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ # verify the required parameter 'order_id' is set if order_id is None: raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`") - + all_params = ['order_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_order_by_id" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method get_order_by_id" % key + ) params[key] = val del params['kwargs'] @@ -198,64 +231,77 @@ class StoreApi(object): method = 'GET' path_params = {} - if 'order_id' in params: - path_params['orderId'] = params['order_id'] - + path_params['orderId'] = params['order_id'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='Order', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='Order', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def delete_order(self, order_id, **kwargs): """ Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.delete_order(order_id, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param str order_id: ID of the order that needs to be deleted (required) - :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ # verify the required parameter 'order_id' is set if order_id is None: raise ValueError("Missing the required parameter `order_id` when calling `delete_order`") - + all_params = ['order_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 delete_order" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method delete_order" % key + ) params[key] = val del params['kwargs'] @@ -263,32 +309,39 @@ class StoreApi(object): method = 'DELETE' path_params = {} - if 'order_id' in params: - path_params['orderId'] = params['order_id'] - + path_params['orderId'] = params['order_id'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - diff --git a/samples/client/petstore/python/swagger_client/apis/user_api.py b/samples/client/petstore/python/swagger_client/apis/user_api.py index b6fad98e829..5d28a5419ec 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/swagger_client/apis/user_api.py @@ -17,7 +17,8 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. """ from __future__ import absolute_import @@ -30,6 +31,7 @@ from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient + class UserApi(object): def __init__(self, api_client=None): @@ -40,34 +42,38 @@ class UserApi(object): if not config.api_client: config.api_client = ApiClient('http://petstore.swagger.io/v2') self.api_client = config.api_client - - + def create_user(self, **kwargs): """ Create user This can only be done by the logged in user. - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_user(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param User body: Created user object - :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['body'] 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 create_user" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method create_user" % key + ) params[key] = val del params['kwargs'] @@ -75,61 +81,74 @@ class UserApi(object): method = 'POST' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - if 'body' in params: body_params = params['body'] - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def create_users_with_array_input(self, **kwargs): """ Creates list of users with given input array - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_users_with_array_input(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param list[User] body: List of user object - :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['body'] 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 create_users_with_array_input" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method create_users_with_array_input" % key + ) params[key] = val del params['kwargs'] @@ -137,61 +156,74 @@ class UserApi(object): method = 'POST' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - if 'body' in params: body_params = params['body'] - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def create_users_with_list_input(self, **kwargs): """ Creates list of users with given input array - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.create_users_with_list_input(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param list[User] body: List of user object - :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['body'] 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 create_users_with_list_input" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method create_users_with_list_input" % key + ) params[key] = val del params['kwargs'] @@ -199,62 +231,75 @@ class UserApi(object): method = 'POST' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - if 'body' in params: body_params = params['body'] - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def login_user(self, **kwargs): """ Logs user into the system - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.login_user(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param str username: The user name for login :param str password: The password for login in clear text - :return: str - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ - + all_params = ['username', 'password'] 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 login_user" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method login_user" % key + ) params[key] = val del params['kwargs'] @@ -262,63 +307,75 @@ class UserApi(object): method = 'GET' path_params = {} - + query_params = {} - if 'username' in params: query_params['username'] = params['username'] - if 'password' in params: query_params['password'] = params['password'] - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='str', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='str', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def logout_user(self, **kwargs): """ Logs out current logged in user session - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.logout_user(callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) - + :param callback function: The callback function + for asynchronous request. (optional) :return: None - If the method is called asynchronously, returns the request thread. + 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 logout_user" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method logout_user" % key + ) params[key] = val del params['kwargs'] @@ -326,61 +383,75 @@ class UserApi(object): method = 'GET' path_params = {} - + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def get_user_by_name(self, username, **kwargs): """ Get user by user name - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.get_user_by_name(username, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param str username: The name that needs to be fetched. Use user1 for testing. (required) - :return: User - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ # verify the required parameter 'username' is set if username is None: raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") - + all_params = ['username'] 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_user_by_name" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method get_user_by_name" % key + ) params[key] = val del params['kwargs'] @@ -388,65 +459,78 @@ class UserApi(object): method = 'GET' path_params = {} - if 'username' in params: - path_params['username'] = params['username'] - + path_params['username'] = params['username'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type='User', auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type='User', + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def update_user(self, username, **kwargs): """ Updated user This can only be done by the logged in user. - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.update_user(username, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param str username: name that need to be deleted (required) :param User body: Updated user object - :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ # verify the required parameter 'username' is set if username is None: raise ValueError("Missing the required parameter `username` when calling `update_user`") - + all_params = ['username', 'body'] 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 update_user" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method update_user" % key + ) params[key] = val del params['kwargs'] @@ -454,67 +538,79 @@ class UserApi(object): method = 'PUT' path_params = {} - if 'username' in params: - path_params['username'] = params['username'] - + path_params['username'] = params['username'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - if 'body' in params: body_params = params['body'] - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - + def delete_user(self, username, **kwargs): """ Delete user This can only be done by the logged in user. - SDK also supports asynchronous requests in which you can define a `callback` function + SDK also supports asynchronous requests + in which you can define a `callback` function to be passed along and invoked when receiving response: >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.delete_user(username, callback=callback_function) - :param callback function: The callback function for asynchronous request. (optional) + :param callback function: The callback function + for asynchronous request. (optional) :param str username: The name that needs to be deleted (required) - :return: None - If the method is called asynchronously, returns the request thread. + If the method is called asynchronously, + returns the request thread. """ # verify the required parameter 'username' is set if username is None: raise ValueError("Missing the required parameter `username` when calling `delete_user`") - + all_params = ['username'] 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 delete_user" % key) + raise TypeError( + "Got an unexpected keyword argument '%s'" + " to method delete_user" % key + ) params[key] = val del params['kwargs'] @@ -522,32 +618,39 @@ class UserApi(object): method = 'DELETE' path_params = {} - if 'username' in params: - path_params['username'] = params['username'] - + path_params['username'] = params['username'] + query_params = {} - + header_params = {} - + form_params = {} files = {} - + body_params = None - + # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) + 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([]) + header_params['Content-Type'] = self.api_client.\ + select_header_content_type([]) # Authentication setting auth_settings = [] - response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, - body=body_params, post_params=form_params, files=files, - response_type=None, auth_settings=auth_settings, callback=params.get('callback')) + response = self.api_client.call_api(resource_path, method, + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback')) return response - diff --git a/samples/client/petstore/python/swagger_client/configuration.py b/samples/client/petstore/python/swagger_client/configuration.py index aff44cd2fa3..0fe945bee1b 100644 --- a/samples/client/petstore/python/swagger_client/configuration.py +++ b/samples/client/petstore/python/swagger_client/configuration.py @@ -5,6 +5,7 @@ import httplib import sys import logging + def singleton(cls, *args, **kw): instances = {} @@ -23,6 +24,8 @@ class Configuration(object): self.host = "http://petstore.swagger.io/v2" # Default api client self.api_client = None + # Temp file folder + self.temp_folder_path = None # Authentication Settings self.api_key = {} self.api_key_prefix = {} @@ -93,22 +96,20 @@ class Configuration(object): def auth_settings(self): """ Return Auth Settings for api client """ - return { - 'api_key': { - 'type': 'api_key', - 'in': 'header', - 'key': 'api_key', - 'value': self.get_api_key_with_prefix('api_key') - }, - - } + return { + 'api_key': + { + 'type': 'api_key', + 'in': 'header', + 'key': 'api_key', + 'value': self.get_api_key_with_prefix('api_key') + }, + } def to_debug_report(self): return "Python SDK Debug Report:\n"\ "OS: {env}\n"\ "Python Version: {pyversion}\n"\ "Version of the API: 1.0.0\n"\ - "SDK Package Version: 1.0.0".format(env=sys.platform, pyversion=sys.version) - - - + "SDK Package Version: 1.0.0".\ + format(env=sys.platform, pyversion=sys.version) diff --git a/samples/client/petstore/python/swagger_client/models/__init__.py b/samples/client/petstore/python/swagger_client/models/__init__.py index de307a26503..236f10e934a 100644 --- a/samples/client/petstore/python/swagger_client/models/__init__.py +++ b/samples/client/petstore/python/swagger_client/models/__init__.py @@ -6,4 +6,3 @@ from .category import Category from .pet import Pet from .tag import Tag from .order import Order - diff --git a/samples/client/petstore/python/swagger_client/models/category.py b/samples/client/petstore/python/swagger_client/models/category.py index f2be305118d..cc9181a378d 100644 --- a/samples/client/petstore/python/swagger_client/models/category.py +++ b/samples/client/petstore/python/swagger_client/models/category.py @@ -17,18 +17,20 @@ Copyright 2015 SmartBear Software limitations under the License. """ + class Category(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): """ Swagger model - :param dict swaggerTypes: The key is attribute name and the value is attribute type. - :param dict attributeMap: The key is attribute name and the value is json key in definition. + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. """ self.swagger_types = { 'id': 'int', @@ -39,38 +41,32 @@ class Category(object): 'id': 'id', 'name': 'name' } - - - self._id = None # int - - - self._name = None # str - - + + self._id = None + self._name = None + @property def id(self): return self._id @id.setter def id(self, id): - self._id = id - + @property def name(self): return self._name @name.setter def name(self, name): - self._name = name - + def __repr__(self): properties = [] for p in self.__dict__: if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) - - return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) - + properties.append('{prop}={val!r}' + .format(prop=p, val=self.__dict__[p])) + return '<{name} {props}>'.format(name=__name__, + props=' '.join(properties)) diff --git a/samples/client/petstore/python/swagger_client/models/order.py b/samples/client/petstore/python/swagger_client/models/order.py index 34774c6c96c..386b0711e56 100644 --- a/samples/client/petstore/python/swagger_client/models/order.py +++ b/samples/client/petstore/python/swagger_client/models/order.py @@ -17,18 +17,20 @@ Copyright 2015 SmartBear Software limitations under the License. """ + class Order(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): """ Swagger model - :param dict swaggerTypes: The key is attribute name and the value is attribute type. - :param dict attributeMap: The key is attribute name and the value is json key in definition. + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. """ self.swagger_types = { 'id': 'int', @@ -47,62 +49,46 @@ class Order(object): 'status': 'status', 'complete': 'complete' } - - - self._id = None # int - - - self._pet_id = None # int - - - self._quantity = None # int - - - self._ship_date = None # datetime - - # Order Status - self._status = None # str - - - self._complete = None # bool - - + + self._id = None + self._pet_id = None + self._quantity = None + self._ship_date = None + self._status = None # Order Status + self._complete = None + @property def id(self): return self._id @id.setter def id(self, id): - self._id = id - + @property def pet_id(self): return self._pet_id @pet_id.setter def pet_id(self, pet_id): - self._pet_id = pet_id - + @property def quantity(self): return self._quantity @quantity.setter def quantity(self, quantity): - self._quantity = quantity - + @property def ship_date(self): return self._ship_date @ship_date.setter def ship_date(self, ship_date): - self._ship_date = ship_date - + @property def status(self): return self._status @@ -111,25 +97,26 @@ class Order(object): def status(self, status): allowed_values = ["placed", "approved", "delivered"] if status not in allowed_values: - raise ValueError("Invalid value for `status`, must be one of {0}".format(allowed_values)) - + raise ValueError( + "Invalid value for `status`, must be one of {0}" + .format(allowed_values) + ) self._status = status - + @property def complete(self): return self._complete @complete.setter def complete(self, complete): - self._complete = complete - + def __repr__(self): properties = [] for p in self.__dict__: if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) - - return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) - + properties.append('{prop}={val!r}' + .format(prop=p, val=self.__dict__[p])) + return '<{name} {props}>'.format(name=__name__, + props=' '.join(properties)) diff --git a/samples/client/petstore/python/swagger_client/models/pet.py b/samples/client/petstore/python/swagger_client/models/pet.py index 37a4ca89b45..ab21f38469d 100644 --- a/samples/client/petstore/python/swagger_client/models/pet.py +++ b/samples/client/petstore/python/swagger_client/models/pet.py @@ -17,18 +17,20 @@ Copyright 2015 SmartBear Software limitations under the License. """ + class Pet(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): """ Swagger model - :param dict swaggerTypes: The key is attribute name and the value is attribute type. - :param dict attributeMap: The key is attribute name and the value is json key in definition. + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. """ self.swagger_types = { 'id': 'int', @@ -47,71 +49,54 @@ class Pet(object): 'tags': 'tags', 'status': 'status' } - - - self._id = None # int - - - self._category = None # Category - - - self._name = None # str - - - self._photo_urls = None # list[str] - - - self._tags = None # list[Tag] - - # pet status in the store - self._status = None # str - - + + self._id = None + self._category = None + self._name = None + self._photo_urls = None + self._tags = None + self._status = None # pet status in the store + @property def id(self): return self._id @id.setter def id(self, id): - self._id = id - + @property def category(self): return self._category @category.setter def category(self, category): - self._category = category - + @property def name(self): return self._name @name.setter def name(self, name): - self._name = name - + @property def photo_urls(self): return self._photo_urls @photo_urls.setter def photo_urls(self, photo_urls): - self._photo_urls = photo_urls - + @property def tags(self): return self._tags @tags.setter def tags(self, tags): - self._tags = tags - + @property def status(self): return self._status @@ -120,16 +105,18 @@ class Pet(object): def status(self, status): allowed_values = ["available", "pending", "sold"] if status not in allowed_values: - raise ValueError("Invalid value for `status`, must be one of {0}".format(allowed_values)) - + raise ValueError( + "Invalid value for `status`, must be one of {0}" + .format(allowed_values) + ) self._status = status - + def __repr__(self): properties = [] for p in self.__dict__: if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) - - return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) - + properties.append('{prop}={val!r}' + .format(prop=p, val=self.__dict__[p])) + return '<{name} {props}>'.format(name=__name__, + props=' '.join(properties)) diff --git a/samples/client/petstore/python/swagger_client/models/tag.py b/samples/client/petstore/python/swagger_client/models/tag.py index 63c1f3291b9..98501f4e954 100644 --- a/samples/client/petstore/python/swagger_client/models/tag.py +++ b/samples/client/petstore/python/swagger_client/models/tag.py @@ -17,18 +17,20 @@ Copyright 2015 SmartBear Software limitations under the License. """ + class Tag(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): """ Swagger model - :param dict swaggerTypes: The key is attribute name and the value is attribute type. - :param dict attributeMap: The key is attribute name and the value is json key in definition. + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. """ self.swagger_types = { 'id': 'int', @@ -39,38 +41,32 @@ class Tag(object): 'id': 'id', 'name': 'name' } - - - self._id = None # int - - - self._name = None # str - - + + self._id = None + self._name = None + @property def id(self): return self._id @id.setter def id(self, id): - self._id = id - + @property def name(self): return self._name @name.setter def name(self, name): - self._name = name - + def __repr__(self): properties = [] for p in self.__dict__: if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) - - return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) - + properties.append('{prop}={val!r}' + .format(prop=p, val=self.__dict__[p])) + return '<{name} {props}>'.format(name=__name__, + props=' '.join(properties)) diff --git a/samples/client/petstore/python/swagger_client/models/user.py b/samples/client/petstore/python/swagger_client/models/user.py index 7049e1e8c97..dd003f95426 100644 --- a/samples/client/petstore/python/swagger_client/models/user.py +++ b/samples/client/petstore/python/swagger_client/models/user.py @@ -17,18 +17,20 @@ Copyright 2015 SmartBear Software limitations under the License. """ + class User(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self): """ Swagger model - :param dict swaggerTypes: The key is attribute name and the value is attribute type. - :param dict attributeMap: The key is attribute name and the value is json key in definition. + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. """ self.swagger_types = { 'id': 'int', @@ -51,110 +53,86 @@ class User(object): 'phone': 'phone', 'user_status': 'userStatus' } - - - self._id = None # int - - - self._username = None # str - - - self._first_name = None # str - - - self._last_name = None # str - - - self._email = None # str - - - self._password = None # str - - - self._phone = None # str - - # User Status - self._user_status = None # int - - + + self._id = None + self._username = None + self._first_name = None + self._last_name = None + self._email = None + self._password = None + self._phone = None + self._user_status = None # User Status + @property def id(self): return self._id @id.setter def id(self, id): - self._id = id - + @property def username(self): return self._username @username.setter def username(self, username): - self._username = username - + @property def first_name(self): return self._first_name @first_name.setter def first_name(self, first_name): - self._first_name = first_name - + @property def last_name(self): return self._last_name @last_name.setter def last_name(self, last_name): - self._last_name = last_name - + @property def email(self): return self._email @email.setter def email(self, email): - self._email = email - + @property def password(self): return self._password @password.setter def password(self, password): - self._password = password - + @property def phone(self): return self._phone @phone.setter def phone(self, phone): - self._phone = phone - + @property def user_status(self): return self._user_status @user_status.setter def user_status(self, user_status): - self._user_status = user_status - + def __repr__(self): properties = [] for p in self.__dict__: if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) - - return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) - + properties.append('{prop}={val!r}' + .format(prop=p, val=self.__dict__[p])) + return '<{name} {props}>'.format(name=__name__, + props=' '.join(properties)) diff --git a/samples/client/petstore/python/swagger_client/rest.py b/samples/client/petstore/python/swagger_client/rest.py index 7cf08f50429..fab813a4cc9 100644 --- a/samples/client/petstore/python/swagger_client/rest.py +++ b/samples/client/petstore/python/swagger_client/rest.py @@ -51,6 +51,7 @@ class RESTResponse(io.IOBase): """ return self.urllib3_response.getheader(name, default) + class RESTClientObject(object): def __init__(self, pools_size=4): @@ -87,14 +88,17 @@ class RESTClientObject(object): :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` - :param post_params: request post parameters, `application/x-www-form-urlencode` + :param post_params: request post parameters, + `application/x-www-form-urlencode` and `multipart/form-data` """ method = method.upper() assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH'] if post_params and body: - raise ValueError("body parameter cannot be used with post_params parameter.") + raise ValueError( + "body parameter cannot be used with post_params parameter." + ) post_params = post_params or {} headers = headers or {} @@ -144,22 +148,37 @@ class RESTClientObject(object): return r def GET(self, url, headers=None, query_params=None): - return self.request("GET", url, headers=headers, query_params=query_params) + return self.request("GET", url, + headers=headers, + query_params=query_params) def HEAD(self, url, headers=None, query_params=None): - return self.request("HEAD", url, headers=headers, query_params=query_params) + return self.request("HEAD", url, + headers=headers, + query_params=query_params) def DELETE(self, url, headers=None, query_params=None): - return self.request("DELETE", url, headers=headers, query_params=query_params) + return self.request("DELETE", url, + headers=headers, + query_params=query_params) def POST(self, url, headers=None, post_params=None, body=None): - return self.request("POST", url, headers=headers, post_params=post_params, body=body) + return self.request("POST", url, + headers=headers, + post_params=post_params, + body=body) def PUT(self, url, headers=None, post_params=None, body=None): - return self.request("PUT", url, headers=headers, post_params=post_params, body=body) + return self.request("PUT", url, + headers=headers, + post_params=post_params, + body=body) def PATCH(self, url, headers=None, post_params=None, body=None): - return self.request("PATCH", url, headers=headers, post_params=post_params, body=body) + return self.request("PATCH", url, + headers=headers, + post_params=post_params, + body=body) class ApiException(Exception): @@ -190,6 +209,7 @@ class ApiException(Exception): return error_message + class RESTClient(object): """ A class with all class methods to perform JSON requests. From c9889c5baffb0f38f3ce361afb260c9f70b79b05 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 18 Jul 2015 15:03:55 +0800 Subject: [PATCH 4/9] Update api template of python client --- .../src/main/resources/python/api.mustache | 2 +- .../python/swagger_client/apis/pet_api.py | 18 +++++++++--------- .../python/swagger_client/apis/store_api.py | 2 +- .../python/swagger_client/apis/user_api.py | 12 ++++++------ 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 94f5af1ffcc..5f738432c25 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -61,7 +61,7 @@ class {{classname}}(object): :param callback function: The callback function for asynchronous request. (optional) {{#allParams}} - :param {{dataType}} {{paramName}}: {{{description}}} {{#required}}(required){{/required}}{{#optional}}(optional){{/optional}} + :param {{dataType}} {{paramName}}: {{{description}}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}} {{/allParams}} :return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}} If the method is called asynchronously, diff --git a/samples/client/petstore/python/swagger_client/apis/pet_api.py b/samples/client/petstore/python/swagger_client/apis/pet_api.py index ad70dac30b3..02d9e647917 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -58,7 +58,7 @@ class PetApi(object): :param callback function: The callback function for asynchronous request. (optional) - :param Pet body: Pet object that needs to be added to the store + :param Pet body: Pet object that needs to be added to the store :return: None If the method is called asynchronously, returns the request thread. @@ -133,7 +133,7 @@ class PetApi(object): :param callback function: The callback function for asynchronous request. (optional) - :param Pet body: Pet object that needs to be added to the store + :param Pet body: Pet object that needs to be added to the store :return: None If the method is called asynchronously, returns the request thread. @@ -208,7 +208,7 @@ class PetApi(object): :param callback function: The callback function for asynchronous request. (optional) - :param list[str] status: Status values that need to be considered for filter + :param list[str] status: Status values that need to be considered for filter :return: list[Pet] If the method is called asynchronously, returns the request thread. @@ -283,7 +283,7 @@ class PetApi(object): :param callback function: The callback function for asynchronous request. (optional) - :param list[str] tags: Tags to filter by + :param list[str] tags: Tags to filter by :return: list[Pet] If the method is called asynchronously, returns the request thread. @@ -437,8 +437,8 @@ class PetApi(object): :param callback function: The callback function for asynchronous request. (optional) :param str pet_id: ID of pet that needs to be updated (required) - :param str name: Updated name of the pet - :param str status: Updated status of the pet + :param str name: Updated name of the pet + :param str status: Updated status of the pet :return: None If the method is called asynchronously, returns the request thread. @@ -521,7 +521,7 @@ class PetApi(object): :param callback function: The callback function for asynchronous request. (optional) :param int pet_id: Pet id to delete (required) - :param str api_key: + :param str api_key: :return: None If the method is called asynchronously, returns the request thread. @@ -602,8 +602,8 @@ class PetApi(object): :param callback function: The callback function for asynchronous request. (optional) :param int pet_id: ID of pet to update (required) - :param str additional_metadata: Additional data to pass to server - :param file file: file to upload + :param str additional_metadata: Additional data to pass to server + :param file file: file to upload :return: None If the method is called asynchronously, returns the request thread. diff --git a/samples/client/petstore/python/swagger_client/apis/store_api.py b/samples/client/petstore/python/swagger_client/apis/store_api.py index 589362cdddd..40b57b0b619 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/swagger_client/apis/store_api.py @@ -130,7 +130,7 @@ class StoreApi(object): :param callback function: The callback function for asynchronous request. (optional) - :param Order body: order placed for purchasing the pet + :param Order body: order placed for purchasing the pet :return: Order If the method is called asynchronously, returns the request thread. diff --git a/samples/client/petstore/python/swagger_client/apis/user_api.py b/samples/client/petstore/python/swagger_client/apis/user_api.py index 5d28a5419ec..fb0898cf782 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/swagger_client/apis/user_api.py @@ -58,7 +58,7 @@ class UserApi(object): :param callback function: The callback function for asynchronous request. (optional) - :param User body: Created user object + :param User body: Created user object :return: None If the method is called asynchronously, returns the request thread. @@ -133,7 +133,7 @@ class UserApi(object): :param callback function: The callback function for asynchronous request. (optional) - :param list[User] body: List of user object + :param list[User] body: List of user object :return: None If the method is called asynchronously, returns the request thread. @@ -208,7 +208,7 @@ class UserApi(object): :param callback function: The callback function for asynchronous request. (optional) - :param list[User] body: List of user object + :param list[User] body: List of user object :return: None If the method is called asynchronously, returns the request thread. @@ -283,8 +283,8 @@ class UserApi(object): :param callback function: The callback function for asynchronous request. (optional) - :param str username: The user name for login - :param str password: The password for login in clear text + :param str username: The user name for login + :param str password: The password for login in clear text :return: str If the method is called asynchronously, returns the request thread. @@ -512,7 +512,7 @@ class UserApi(object): :param callback function: The callback function for asynchronous request. (optional) :param str username: name that need to be deleted (required) - :param User body: Updated user object + :param User body: Updated user object :return: None If the method is called asynchronously, returns the request thread. From ddfa713f55c29cf8c51301b4b1229890275744aa Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 18 Jul 2015 15:22:39 +0800 Subject: [PATCH 5/9] Update wording of comment in api template of python client --- .../src/main/resources/python/api.mustache | 4 +++ .../python/swagger_client/apis/pet_api.py | 32 +++++++++++++++++++ .../python/swagger_client/apis/store_api.py | 16 ++++++++++ .../python/swagger_client/apis/user_api.py | 32 +++++++++++++++++++ 4 files changed, 84 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 5f738432c25..61818ef179e 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -58,6 +58,10 @@ class {{classname}}(object): >>> >>> thread = api.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) {{#allParams}} diff --git a/samples/client/petstore/python/swagger_client/apis/pet_api.py b/samples/client/petstore/python/swagger_client/apis/pet_api.py index 02d9e647917..fa715a2be32 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -56,6 +56,10 @@ class PetApi(object): >>> >>> thread = api.update_pet(callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param Pet body: Pet object that needs to be added to the store @@ -131,6 +135,10 @@ class PetApi(object): >>> >>> thread = api.add_pet(callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param Pet body: Pet object that needs to be added to the store @@ -206,6 +214,10 @@ class PetApi(object): >>> >>> thread = api.find_pets_by_status(callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param list[str] status: Status values that need to be considered for filter @@ -281,6 +293,10 @@ class PetApi(object): >>> >>> thread = api.find_pets_by_tags(callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param list[str] tags: Tags to filter by @@ -356,6 +372,10 @@ class PetApi(object): >>> >>> thread = api.get_pet_by_id(pet_id, callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param int pet_id: ID of pet that needs to be fetched (required) @@ -434,6 +454,10 @@ class PetApi(object): >>> >>> thread = api.update_pet_with_form(pet_id, callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param str pet_id: ID of pet that needs to be updated (required) @@ -518,6 +542,10 @@ class PetApi(object): >>> >>> thread = api.delete_pet(pet_id, callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param int pet_id: Pet id to delete (required) @@ -599,6 +627,10 @@ class PetApi(object): >>> >>> thread = api.upload_file(pet_id, callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param int pet_id: ID of pet to update (required) diff --git a/samples/client/petstore/python/swagger_client/apis/store_api.py b/samples/client/petstore/python/swagger_client/apis/store_api.py index 40b57b0b619..ed63c3f1652 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/swagger_client/apis/store_api.py @@ -56,6 +56,10 @@ class StoreApi(object): >>> >>> thread = api.get_inventory(callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :return: dict(str, int) @@ -128,6 +132,10 @@ class StoreApi(object): >>> >>> thread = api.place_order(callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param Order body: order placed for purchasing the pet @@ -203,6 +211,10 @@ class StoreApi(object): >>> >>> thread = api.get_order_by_id(order_id, callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param str order_id: ID of pet that needs to be fetched (required) @@ -281,6 +293,10 @@ class StoreApi(object): >>> >>> thread = api.delete_order(order_id, callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param str order_id: ID of the order that needs to be deleted (required) diff --git a/samples/client/petstore/python/swagger_client/apis/user_api.py b/samples/client/petstore/python/swagger_client/apis/user_api.py index fb0898cf782..b98fd09c9dd 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/swagger_client/apis/user_api.py @@ -56,6 +56,10 @@ class UserApi(object): >>> >>> thread = api.create_user(callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param User body: Created user object @@ -131,6 +135,10 @@ class UserApi(object): >>> >>> thread = api.create_users_with_array_input(callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param list[User] body: List of user object @@ -206,6 +214,10 @@ class UserApi(object): >>> >>> thread = api.create_users_with_list_input(callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param list[User] body: List of user object @@ -281,6 +293,10 @@ class UserApi(object): >>> >>> thread = api.login_user(callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param str username: The user name for login @@ -359,6 +375,10 @@ class UserApi(object): >>> >>> thread = api.logout_user(callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :return: None @@ -431,6 +451,10 @@ class UserApi(object): >>> >>> thread = api.get_user_by_name(username, callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param str username: The name that needs to be fetched. Use user1 for testing. (required) @@ -509,6 +533,10 @@ class UserApi(object): >>> >>> thread = api.update_user(username, callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param str username: name that need to be deleted (required) @@ -590,6 +618,10 @@ class UserApi(object): >>> >>> thread = api.delete_user(username, callback=callback_function) + 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. + :param callback function: The callback function for asynchronous request. (optional) :param str username: The name that needs to be deleted (required) From 195c71da377cf50bdb0c8f8236120c230a75db95 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 18 Jul 2015 15:35:12 +0800 Subject: [PATCH 6/9] Update comments of python client --- .../src/main/resources/python/api.mustache | 11 +-- .../python/swagger_client/apis/pet_api.py | 88 +++++++------------ .../python/swagger_client/apis/store_api.py | 44 ++++------ .../python/swagger_client/apis/user_api.py | 88 +++++++------------ 4 files changed, 84 insertions(+), 147 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 61818ef179e..8fde001f0ba 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -50,18 +50,15 @@ class {{classname}}(object): {{{summary}}} {{{notes}}} - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) {{#allParams}} diff --git a/samples/client/petstore/python/swagger_client/apis/pet_api.py b/samples/client/petstore/python/swagger_client/apis/pet_api.py index fa715a2be32..299e6dc73b2 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -48,18 +48,15 @@ class PetApi(object): Update an existing pet - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.update_pet(callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param Pet body: Pet object that needs to be added to the store @@ -127,18 +124,15 @@ class PetApi(object): Add a new pet to the store - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.add_pet(callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param Pet body: Pet object that needs to be added to the store @@ -206,18 +200,15 @@ class PetApi(object): Finds Pets by status Multiple status values can be provided with comma seperated strings - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.find_pets_by_status(callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param list[str] status: Status values that need to be considered for filter @@ -285,18 +276,15 @@ class PetApi(object): Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.find_pets_by_tags(callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param list[str] tags: Tags to filter by @@ -364,18 +352,15 @@ class PetApi(object): Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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(pet_id, callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param int pet_id: ID of pet that needs to be fetched (required) @@ -446,18 +431,15 @@ class PetApi(object): Updates a pet in the store with form data - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.update_pet_with_form(pet_id, callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param str pet_id: ID of pet that needs to be updated (required) @@ -534,18 +516,15 @@ class PetApi(object): Deletes a pet - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.delete_pet(pet_id, callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param int pet_id: Pet id to delete (required) @@ -619,18 +598,15 @@ class PetApi(object): uploads an image - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.upload_file(pet_id, callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param int pet_id: ID of pet to update (required) diff --git a/samples/client/petstore/python/swagger_client/apis/store_api.py b/samples/client/petstore/python/swagger_client/apis/store_api.py index ed63c3f1652..76506e1b9a3 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/swagger_client/apis/store_api.py @@ -48,18 +48,15 @@ class StoreApi(object): Returns pet inventories by status Returns a map of status codes to quantities - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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(callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :return: dict(str, int) @@ -124,18 +121,15 @@ class StoreApi(object): Place an order for a pet - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.place_order(callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param Order body: order placed for purchasing the pet @@ -203,18 +197,15 @@ class StoreApi(object): Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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_order_by_id(order_id, callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param str order_id: ID of pet that needs to be fetched (required) @@ -285,18 +276,15 @@ class StoreApi(object): Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.delete_order(order_id, callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param str order_id: ID of the order that needs to be deleted (required) diff --git a/samples/client/petstore/python/swagger_client/apis/user_api.py b/samples/client/petstore/python/swagger_client/apis/user_api.py index b98fd09c9dd..88deb1803ec 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/swagger_client/apis/user_api.py @@ -48,18 +48,15 @@ class UserApi(object): Create user This can only be done by the logged in user. - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.create_user(callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param User body: Created user object @@ -127,18 +124,15 @@ class UserApi(object): Creates list of users with given input array - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.create_users_with_array_input(callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param list[User] body: List of user object @@ -206,18 +200,15 @@ class UserApi(object): Creates list of users with given input array - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.create_users_with_list_input(callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param list[User] body: List of user object @@ -285,18 +276,15 @@ class UserApi(object): Logs user into the system - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.login_user(callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param str username: The user name for login @@ -367,18 +355,15 @@ class UserApi(object): Logs out current logged in user session - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.logout_user(callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :return: None @@ -443,18 +428,15 @@ class UserApi(object): Get user by user name - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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_user_by_name(username, callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param str username: The name that needs to be fetched. Use user1 for testing. (required) @@ -525,18 +507,15 @@ class UserApi(object): Updated user This can only be done by the logged in user. - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.update_user(username, callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param str username: name that need to be deleted (required) @@ -610,18 +589,15 @@ class UserApi(object): Delete user This can only be done by the logged in user. - SDK also supports asynchronous requests - in which you can define a `callback` function - to be passed along and invoked when receiving response: + 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.delete_user(username, callback=callback_function) - 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. - :param callback function: The callback function for asynchronous request. (optional) :param str username: The name that needs to be deleted (required) From 68820e5a8036c8297c29bdea9b20da5af398375f Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 18 Jul 2015 15:54:00 +0800 Subject: [PATCH 7/9] Update comments of api template of python client --- .../src/main/resources/python/api.mustache | 5 +-- .../python/swagger_client/apis/pet_api.py | 40 ++++++++----------- .../python/swagger_client/apis/store_api.py | 20 ++++------ .../python/swagger_client/apis/user_api.py | 40 ++++++++----------- 4 files changed, 42 insertions(+), 63 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 8fde001f0ba..9811288e929 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -50,9 +50,8 @@ class {{classname}}(object): {{{summary}}} {{{notes}}} - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) diff --git a/samples/client/petstore/python/swagger_client/apis/pet_api.py b/samples/client/petstore/python/swagger_client/apis/pet_api.py index 299e6dc73b2..3f3e523a15a 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -48,9 +48,8 @@ class PetApi(object): Update an existing pet - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) @@ -124,9 +123,8 @@ class PetApi(object): Add a new pet to the store - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) @@ -200,9 +198,8 @@ class PetApi(object): Finds Pets by status Multiple status values can be provided with comma seperated strings - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) @@ -276,9 +273,8 @@ class PetApi(object): Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) @@ -352,9 +348,8 @@ class PetApi(object): 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 + 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) @@ -431,9 +426,8 @@ class PetApi(object): Updates a pet in the store with form data - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) @@ -516,9 +510,8 @@ class PetApi(object): Deletes a pet - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) @@ -598,9 +591,8 @@ class PetApi(object): uploads an image - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) diff --git a/samples/client/petstore/python/swagger_client/apis/store_api.py b/samples/client/petstore/python/swagger_client/apis/store_api.py index 76506e1b9a3..ac465f792ec 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/swagger_client/apis/store_api.py @@ -48,9 +48,8 @@ class StoreApi(object): Returns pet inventories by status Returns 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 + 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) @@ -121,9 +120,8 @@ class StoreApi(object): Place an order for a pet - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) @@ -197,9 +195,8 @@ class StoreApi(object): Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) @@ -276,9 +273,8 @@ class StoreApi(object): Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) diff --git a/samples/client/petstore/python/swagger_client/apis/user_api.py b/samples/client/petstore/python/swagger_client/apis/user_api.py index 88deb1803ec..0469e83ae2f 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/swagger_client/apis/user_api.py @@ -48,9 +48,8 @@ class UserApi(object): Create user This can only be done by the logged in user. - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) @@ -124,9 +123,8 @@ class UserApi(object): Creates list of users with given input array - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) @@ -200,9 +198,8 @@ class UserApi(object): Creates list of users with given input array - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) @@ -276,9 +273,8 @@ class UserApi(object): Logs user into the system - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) @@ -355,9 +351,8 @@ class UserApi(object): Logs out current logged in user session - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) @@ -428,9 +423,8 @@ class UserApi(object): Get user by user name - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) @@ -507,9 +501,8 @@ class UserApi(object): Updated user This can only be done by the logged in user. - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) @@ -589,9 +582,8 @@ class UserApi(object): Delete user This can only be done by the logged in user. - This method makes a synchronous HTTP request by default. - To make an asynchronous HTTP request, - please define a `callback` function + 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) From b9287cf417805677d69b7f4769492f7119be0a2a Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 22 Jul 2015 11:00:51 +0800 Subject: [PATCH 8/9] Add to_str method in python client and add test cases. --- .../src/main/resources/python/model.mustache | 41 +++++++++++++++---- .../python/swagger_client/models/category.py | 41 +++++++++++++++---- .../python/swagger_client/models/order.py | 41 +++++++++++++++---- .../python/swagger_client/models/pet.py | 41 +++++++++++++++---- .../python/swagger_client/models/tag.py | 41 +++++++++++++++---- .../python/swagger_client/models/user.py | 41 +++++++++++++++---- .../petstore/python/tests/test_pet_model.py | 40 ++++++++++++++++++ 7 files changed, 238 insertions(+), 48 deletions(-) create mode 100644 samples/client/petstore/python/tests/test_pet_model.py diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 2394cd955f3..7314e9ee9cd 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -18,6 +18,8 @@ Copyright 2015 SmartBear Software """ {{#models}} {{#model}} +from pprint import pformat +from six import iteritems class {{classname}}(object): @@ -64,14 +66,37 @@ class {{classname}}(object): {{/isEnum}}self._{{name}} = {{name}} {{/vars}} - def __repr__(self): - properties = [] - for p in self.__dict__: - if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}' - .format(prop=p, val=self.__dict__[p])) + def to_dict(self): + """ + Return model properties dict + """ + result = {} - return '<{name} {props}>'.format(name=__name__, - props=' '.join(properties)) + for name, prop in iteritems(self.__dict__): + if name == "attribute_map" or name == "swagger_types": + continue + if isinstance(prop, list): + result[name[1:]] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + prop + )) + elif hasattr(prop, "to_dict"): + result[name[1:]] = prop.to_dict() + else: + result[name[1:]] = prop + + return result + + def to_str(self): + """ + Return model properties str + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() {{/model}} {{/models}} diff --git a/samples/client/petstore/python/swagger_client/models/category.py b/samples/client/petstore/python/swagger_client/models/category.py index cc9181a378d..ae03bb7ec78 100644 --- a/samples/client/petstore/python/swagger_client/models/category.py +++ b/samples/client/petstore/python/swagger_client/models/category.py @@ -16,6 +16,8 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. """ +from pprint import pformat +from six import iteritems class Category(object): @@ -61,12 +63,35 @@ class Category(object): def name(self, name): self._name = name - def __repr__(self): - properties = [] - for p in self.__dict__: - if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}' - .format(prop=p, val=self.__dict__[p])) + def to_dict(self): + """ + Return model properties dict + """ + result = {} - return '<{name} {props}>'.format(name=__name__, - props=' '.join(properties)) + for name, prop in iteritems(self.__dict__): + if name == "attribute_map" or name == "swagger_types": + continue + if isinstance(prop, list): + result[name[1:]] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + prop + )) + elif hasattr(prop, "to_dict"): + result[name[1:]] = prop.to_dict() + else: + result[name[1:]] = prop + + return result + + def to_str(self): + """ + Return model properties str + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() diff --git a/samples/client/petstore/python/swagger_client/models/order.py b/samples/client/petstore/python/swagger_client/models/order.py index 386b0711e56..7498561372e 100644 --- a/samples/client/petstore/python/swagger_client/models/order.py +++ b/samples/client/petstore/python/swagger_client/models/order.py @@ -16,6 +16,8 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. """ +from pprint import pformat +from six import iteritems class Order(object): @@ -111,12 +113,35 @@ class Order(object): def complete(self, complete): self._complete = complete - def __repr__(self): - properties = [] - for p in self.__dict__: - if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}' - .format(prop=p, val=self.__dict__[p])) + def to_dict(self): + """ + Return model properties dict + """ + result = {} - return '<{name} {props}>'.format(name=__name__, - props=' '.join(properties)) + for name, prop in iteritems(self.__dict__): + if name == "attribute_map" or name == "swagger_types": + continue + if isinstance(prop, list): + result[name[1:]] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + prop + )) + elif hasattr(prop, "to_dict"): + result[name[1:]] = prop.to_dict() + else: + result[name[1:]] = prop + + return result + + def to_str(self): + """ + Return model properties str + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() diff --git a/samples/client/petstore/python/swagger_client/models/pet.py b/samples/client/petstore/python/swagger_client/models/pet.py index ab21f38469d..62f7bea7fd2 100644 --- a/samples/client/petstore/python/swagger_client/models/pet.py +++ b/samples/client/petstore/python/swagger_client/models/pet.py @@ -16,6 +16,8 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. """ +from pprint import pformat +from six import iteritems class Pet(object): @@ -111,12 +113,35 @@ class Pet(object): ) self._status = status - def __repr__(self): - properties = [] - for p in self.__dict__: - if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}' - .format(prop=p, val=self.__dict__[p])) + def to_dict(self): + """ + Return model properties dict + """ + result = {} - return '<{name} {props}>'.format(name=__name__, - props=' '.join(properties)) + for name, prop in iteritems(self.__dict__): + if name == "attribute_map" or name == "swagger_types": + continue + if isinstance(prop, list): + result[name[1:]] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + prop + )) + elif hasattr(prop, "to_dict"): + result[name[1:]] = prop.to_dict() + else: + result[name[1:]] = prop + + return result + + def to_str(self): + """ + Return model properties str + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() diff --git a/samples/client/petstore/python/swagger_client/models/tag.py b/samples/client/petstore/python/swagger_client/models/tag.py index 98501f4e954..ea07acacfdb 100644 --- a/samples/client/petstore/python/swagger_client/models/tag.py +++ b/samples/client/petstore/python/swagger_client/models/tag.py @@ -16,6 +16,8 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. """ +from pprint import pformat +from six import iteritems class Tag(object): @@ -61,12 +63,35 @@ class Tag(object): def name(self, name): self._name = name - def __repr__(self): - properties = [] - for p in self.__dict__: - if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}' - .format(prop=p, val=self.__dict__[p])) + def to_dict(self): + """ + Return model properties dict + """ + result = {} - return '<{name} {props}>'.format(name=__name__, - props=' '.join(properties)) + for name, prop in iteritems(self.__dict__): + if name == "attribute_map" or name == "swagger_types": + continue + if isinstance(prop, list): + result[name[1:]] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + prop + )) + elif hasattr(prop, "to_dict"): + result[name[1:]] = prop.to_dict() + else: + result[name[1:]] = prop + + return result + + def to_str(self): + """ + Return model properties str + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() diff --git a/samples/client/petstore/python/swagger_client/models/user.py b/samples/client/petstore/python/swagger_client/models/user.py index dd003f95426..d81a73318e7 100644 --- a/samples/client/petstore/python/swagger_client/models/user.py +++ b/samples/client/petstore/python/swagger_client/models/user.py @@ -16,6 +16,8 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. """ +from pprint import pformat +from six import iteritems class User(object): @@ -127,12 +129,35 @@ class User(object): def user_status(self, user_status): self._user_status = user_status - def __repr__(self): - properties = [] - for p in self.__dict__: - if p != 'swaggerTypes' and p != 'attributeMap': - properties.append('{prop}={val!r}' - .format(prop=p, val=self.__dict__[p])) + def to_dict(self): + """ + Return model properties dict + """ + result = {} - return '<{name} {props}>'.format(name=__name__, - props=' '.join(properties)) + for name, prop in iteritems(self.__dict__): + if name == "attribute_map" or name == "swagger_types": + continue + if isinstance(prop, list): + result[name[1:]] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + prop + )) + elif hasattr(prop, "to_dict"): + result[name[1:]] = prop.to_dict() + else: + result[name[1:]] = prop + + return result + + def to_str(self): + """ + Return model properties str + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() diff --git a/samples/client/petstore/python/tests/test_pet_model.py b/samples/client/petstore/python/tests/test_pet_model.py new file mode 100644 index 00000000000..0b0df18a8d0 --- /dev/null +++ b/samples/client/petstore/python/tests/test_pet_model.py @@ -0,0 +1,40 @@ +# coding: utf-8 + +""" +Run the tests. +$ pip install nose (optional) +$ cd swagger_client-python +$ nosetests -v +""" + +import os +import time +import unittest + +import swagger_client + + +class PetModelTests(unittest.TestCase): + + def setUp(self): + self.pet = swagger_client.Pet() + self.pet.name = "test name" + self.pet.id = 1 + self.pet.photo_urls = ["string"] + self.pet.status = "available" + cate = swagger_client.Category() + cate.id = 1 + cate.name = "dog" + self.pet.category = cate + tag = swagger_client.Tag() + tag.id = 1 + self.pet.tags = [tag] + + def test_to_str(self): + data = ("{'category': {'id': 1, 'name': 'dog'},\n" + " 'id': 1,\n" + " 'name': 'test name',\n" + " 'photo_urls': ['string'],\n" + " 'status': 'available',\n" + " 'tags': [{'id': 1, 'name': None}]}") + self.assertEqual(data, self.pet.to_str()) From bd6fa6a2e4012afdee105fefe2704e186e041cff Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 22 Jul 2015 15:50:40 +0800 Subject: [PATCH 9/9] Update PetApiTests#test_find_pet_by_tags test case of python client --- samples/client/petstore/python/tests/test_pet_api.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/client/petstore/python/tests/test_pet_api.py b/samples/client/petstore/python/tests/test_pet_api.py index f78a301a9dc..6994ddbd649 100644 --- a/samples/client/petstore/python/tests/test_pet_api.py +++ b/samples/client/petstore/python/tests/test_pet_api.py @@ -35,7 +35,7 @@ class PetApiTests(unittest.TestCase): self.category.name = "dog" self.tag = swagger_client.Tag() self.tag.id = int(time.time()) - self.tag.name = "blank" + self.tag.name = "swagger-codegen-python-pet-tag" self.pet = swagger_client.Pet() self.pet.id = int(time.time()) self.pet.name = "hello kity"