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.