Format python client using pep8

This commit is contained in:
geekerzp 2015-07-18 14:30:19 +08:00
parent 3993ef3dc8
commit 60d6cd744a
20 changed files with 1802 additions and 1391 deletions

View File

@ -1,5 +1,8 @@
from __future__ import absolute_import from __future__ import absolute_import
# import apis into api package # import apis into api package
{{#apiInfo}}{{#apis}}from .{{classVarName}} import {{classname}} {{#apiInfo}}
{{/apis}}{{/apiInfo}} {{#apis}}
from .{{classVarName}} import {{classname}}
{{/apis}}
{{/apiInfo}}

View File

@ -1,5 +1,5 @@
from __future__ import absolute_import from __future__ import absolute_import
# import models into model package # import models into model package
{{#models}}{{#model}}from .{{classVarName}} import {{classname}} {{#models}}{{#model}}from .{{classVarName}} import {{classname}}{{/model}}
{{/model}}{{/models}} {{/models}}

View File

@ -17,7 +17,8 @@ Copyright 2015 SmartBear Software
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. 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 from __future__ import absolute_import
@ -30,6 +31,7 @@ from six import iteritems
from ..configuration import Configuration from ..configuration import Configuration
from ..api_client import ApiClient from ..api_client import ApiClient
{{#operations}} {{#operations}}
class {{classname}}(object): class {{classname}}(object):
@ -41,37 +43,48 @@ class {{classname}}(object):
if not config.api_client: if not config.api_client:
config.api_client = ApiClient('{{basePath}}') config.api_client = ApiClient('{{basePath}}')
self.api_client = config.api_client self.api_client = config.api_client
{{#operation}}
{{#operation}}
def {{nickname}}(self, {{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}**kwargs): def {{nickname}}(self, {{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}**kwargs):
""" """
{{{summary}}} {{{summary}}}
{{{notes}}} {{{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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}callback=callback_function) >>> thread = api.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}callback=callback_function)
:param callback function: The callback function for asynchronous request. (optional) :param callback function: The callback function
{{#allParams}}:param {{dataType}} {{paramName}}: {{{description}}} {{#required}}(required){{/required}}{{#optional}}(optional){{/optional}} for asynchronous request. (optional)
{{/allParams}} {{#allParams}}
:param {{dataType}} {{paramName}}: {{{description}}} {{#required}}(required){{/required}}{{#optional}}(optional){{/optional}}
{{/allParams}}
:return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}} :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: if {{paramName}} is None:
raise ValueError("Missing the required parameter `{{paramName}}` when calling `{{nickname}}`") raise ValueError("Missing the required parameter `{{paramName}}` when calling `{{nickname}}`")
{{/required}}{{/allParams}} {{/required}}
{{/allParams}}
all_params = [{{#allParams}}'{{paramName}}'{{#hasMore}}, {{/hasMore}}{{/allParams}}] all_params = [{{#allParams}}'{{paramName}}'{{#hasMore}}, {{/hasMore}}{{/allParams}}]
all_params.append('callback') all_params.append('callback')
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -79,45 +92,59 @@ class {{classname}}(object):
method = '{{httpMethod}}' method = '{{httpMethod}}'
path_params = {} path_params = {}
{{#pathParams}} {{#pathParams}}
if '{{paramName}}' in params: if '{{paramName}}' in params:
path_params['{{baseName}}'] = params['{{paramName}}'] path_params['{{baseName}}'] = params['{{paramName}}']
{{/pathParams}} {{/pathParams}}
query_params = {} query_params = {}
{{#queryParams}} {{#queryParams}}
if '{{paramName}}' in params: if '{{paramName}}' in params:
query_params['{{baseName}}'] = params['{{paramName}}'] query_params['{{baseName}}'] = params['{{paramName}}']
{{/queryParams}} {{/queryParams}}
header_params = {} header_params = {}
{{#headerParams}} {{#headerParams}}
if '{{paramName}}' in params: if '{{paramName}}' in params:
header_params['{{baseName}}'] = params['{{paramName}}'] header_params['{{baseName}}'] = params['{{paramName}}']
{{/headerParams}} {{/headerParams}}
form_params = {} form_params = {}
files = {} files = {}
{{#formParams}} {{#formParams}}
if '{{paramName}}' in params: if '{{paramName}}' in params:
{{#notFile}}form_params['{{baseName}}'] = params['{{paramName}}']{{/notFile}}{{#isFile}}files['{{baseName}}'] = params['{{paramName}}']{{/isFile}} {{#notFile}}form_params['{{baseName}}'] = params['{{paramName}}']{{/notFile}}{{#isFile}}files['{{baseName}}'] = params['{{paramName}}']{{/isFile}}
{{/formParams}} {{/formParams}}
body_params = None body_params = None
{{#bodyParam}} {{#bodyParam}}
if '{{paramName}}' in params: if '{{paramName}}' in params:
body_params = params['{{paramName}}'] body_params = params['{{paramName}}']
{{/bodyParam}} {{/bodyParam}}
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}]
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, auth_settings=auth_settings, callback=params.get('callback')) 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 return response
{{/operation}} {{/operation}}
{{/operations}} {{/operations}}

View File

@ -27,415 +27,480 @@ from datetime import date
from six import iteritems from six import iteritems
try: try:
# for python3 # for python3
from urllib.parse import quote from urllib.parse import quote
except ImportError: except ImportError:
# for python2 # for python2
from urllib import quote from urllib import quote
from .configuration import Configuration from .configuration import Configuration
class ApiClient(object): 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 :param host: The base path for the server to call
:param header_name: a header to pass when making calls to the API
:return string: quoted value :param header_value: a header value to pass when making calls to the API
""" """
if type(obj) == list: def __init__(self, host=Configuration().host,
return ','.join(obj) header_name=None, header_value=None):
else:
return str(obj)
def sanitize_for_serialization(self, obj): self.default_headers = {}
""" if header_name is not None:
Sanitize an object for Request. 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. @property
If obj is str, int, float, bool, return directly. def user_agent(self):
If obj is datetime.datetime, datetime.date convert to string in iso8601 format. return self.default_headers['User-Agent']
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)}
def deserialize(self, response, response_type): @user_agent.setter
""" def user_agent(self, value):
Derialize response into an object. self.default_headers['User-Agent'] = value
:param response: RESTResponse object to be deserialized def set_default_header(self, header_name, header_value):
:param response_type: class literal for deserialzied object, or string of class name self.default_headers[header_name] = header_value
:return: deserialized object def __call_api(self, resource_path, method,
""" path_params=None, query_params=None, header_params=None,
# handle file downloading - save response body into a tmp file and return the instance body=None, post_params=None, files=None,
if "file" == response_type: response_type=None, auth_settings=None, callback=None):
return self.__deserialize_file(response)
# fetch data from response object # headers parameters
try: header_params = header_params or {}
data = json.loads(response.data) header_params.update(self.default_headers)
except ValueError: if self.cookie:
data = response.data 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): # query parameters
""" if query_params:
:param data: dict, list or str query_params = self.sanitize_for_serialization(query_params)
:param klass: class literal, or string of class name query_params = {k: self.to_path_value(v)
for k, v in iteritems(query_params)}
:return: object # post parameters
""" if post_params:
if data is None: post_params = self.prepare_post_parameters(post_params, files)
return None post_params = self.sanitize_for_serialization(post_params)
if type(klass) == str: # auth setting
if 'list[' in klass: self.update_params_for_auth(header_params, query_params, auth_settings)
sub_kls = re.match('list\[(.*)\]', klass).group(1)
return [self.__deserialize(sub_data, sub_kls) for sub_data in data]
if 'dict(' in klass: # body
sub_kls = re.match('dict\((.*), (.*)\)', klass).group(2) if body:
return {k: self.__deserialize(v, sub_kls) for k, v in iteritems(data)} body = self.sanitize_for_serialization(body)
# convert str to class # request url
# for native types url = self.host + resource_path
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]: # perform request and return response
return self.__deserialize_primitive(data, klass) response_data = self.request(method, url,
elif klass == object: query_params=query_params,
return self.__deserialize_object() headers=header_params,
elif klass == date: post_params=post_params, body=body)
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, self.last_response = response_data
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
# deserialize response data
:param resource_path: Path to method endpoint. if response_type:
:param method: Method to call. deserialized_data = self.deserialize(response_data, response_type)
: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']
else: else:
raise ValueError('Authentication token must be in `query` or `header`') deserialized_data = None
def __deserialize_file(self, response): if callback:
""" callback(deserialized_data)
Save response body into a file in (the defined) temporary folder, using the filename else:
from the `Content-Disposition` header if provided, otherwise a random filename. return deserialized_data
:param response: RESTResponse def to_path_value(self, obj):
:return: file path """
""" Convert a string or object to a path-friendly value
fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path)
os.close(fd)
os.remove(path)
content_disposition = response.getheader("Content-Disposition") :param obj: object or string value
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: :return string: quoted value
f.write(response.data) """
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): If obj is None, return None.
""" If obj is str, int, float, bool, return directly.
Deserialize string to primitive type 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 return {key: self.sanitize_for_serialization(val)
:param klass: class literal for key, val in iteritems(obj_dict)}
:return: int, float, str, bool def deserialize(self, response, response_type):
""" """
try: Derialize response into an object.
value = klass(data)
except UnicodeEncodeError:
value = unicode(data)
except TypeError:
value = data
return value
def __deserialize_object(self): :param response: RESTResponse object to be deserialized
""" :param response_type: class literal for
Deserialize empty object deserialzied object, or string of class name
"""
return object()
def __deserialize_date(self, string): :return: deserialized object
""" """
Deserialize string to date # 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 # fetch data from response object
:return: date try:
""" data = json.loads(response.data)
try: except ValueError:
from dateutil.parser import parse data = response.data
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): return self.__deserialize(data, response_type)
"""
Deserialize string to datetime.
The string should be in iso8601 datetime format. def __deserialize(self, data, klass):
"""
:param data: dict, list or str
:param klass: class literal, or string of class name
:param string: str :return: object
:return: datetime """
""" if data is None:
try: return None
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): if type(klass) == str:
""" if 'list[' in klass:
Deserialize list or dict to model sub_kls = re.match('list\[(.*)\]', klass).group(1)
return [self.__deserialize(sub_data, sub_kls)
for sub_data in data]
:param data: dict, list if 'dict(' in klass:
:param klass: class literal sub_kls = re.match('dict\((.*), (.*)\)', klass).group(2)
""" return {k: self.__deserialize(v, sub_kls)
instance = klass() for k, v in iteritems(data)}
for attr, attr_type in iteritems(instance.swagger_types): # convert str to class
if data is not None \ # for native types
and instance.attribute_map[attr] in data\ if klass in ['int', 'float', 'str', 'bool',
and isinstance(data, (list, dict)): "date", 'datetime', "object"]:
value = data[instance.attribute_map[attr]] klass = eval(klass)
setattr(instance, attr, self.__deserialize(value, attr_type)) # for model types
else:
klass = eval('models.' + klass)
return instance 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

View File

@ -5,6 +5,7 @@ import httplib
import sys import sys
import logging import logging
def singleton(cls, *args, **kw): def singleton(cls, *args, **kw):
instances = {} instances = {}
@ -23,6 +24,8 @@ class Configuration(object):
self.host = "{{basePath}}" self.host = "{{basePath}}"
# Default api client # Default api client
self.api_client = None self.api_client = None
# Temp file folder
self.temp_folder_path = None
# Authentication Settings # Authentication Settings
self.api_key = {} self.api_key = {}
self.api_key_prefix = {} self.api_key_prefix = {}
@ -93,29 +96,33 @@ class Configuration(object):
def auth_settings(self): def auth_settings(self):
""" Return Auth Settings for api client """ """ Return Auth Settings for api client """
return { {{#authMethods}}{{#isApiKey}} return {
'{{name}}': { {{#authMethods}}
'type': 'api_key', {{#isApiKey}}
'in': {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}, '{{name}}':
'key': '{{keyParamName}}', {
'value': self.get_api_key_with_prefix('{{keyParamName}}') 'type': 'api_key',
}, 'in': {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}},
{{/isApiKey}}{{#isBasic}} 'key': '{{keyParamName}}',
'{{name}}': { 'value': self.get_api_key_with_prefix('{{keyParamName}}')
'type': 'basic', },
'in': 'header', {{/isApiKey}}
'key': 'Authorization', {{#isBasic}}
'value': self.get_basic_auth_token() '{{name}}':
}, {
{{/isBasic}}{{/authMethods}} 'type': 'basic',
} 'in': 'header',
'key': 'Authorization',
'value': self.get_basic_auth_token()
},
{{/isBasic}}
{{/authMethods}}
}
def to_debug_report(self): def to_debug_report(self):
return "Python SDK Debug Report:\n"\ return "Python SDK Debug Report:\n"\
"OS: {env}\n"\ "OS: {env}\n"\
"Python Version: {pyversion}\n"\ "Python Version: {pyversion}\n"\
"Version of the API: {{version}}\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)

View File

@ -19,18 +19,20 @@ Copyright 2015 SmartBear Software
{{#models}} {{#models}}
{{#model}} {{#model}}
class {{classname}}(object): class {{classname}}(object):
""" """
NOTE: This class is auto generated by the swagger code generator program. NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. Do not edit the class manually.
""" """
def __init__(self): def __init__(self):
""" """
Swagger model Swagger model
:param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict swaggerTypes: The key is attribute name
:param dict attributeMap: The key is attribute name and the value is json key in definition. 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 = { self.swagger_types = {
{{#vars}}'{{name}}': '{{{datatype}}}'{{#hasMore}}, {{#vars}}'{{name}}': '{{{datatype}}}'{{#hasMore}},
@ -41,11 +43,12 @@ class {{classname}}(object):
{{#vars}}'{{name}}': '{{baseName}}'{{#hasMore}}, {{#vars}}'{{name}}': '{{baseName}}'{{#hasMore}},
{{/hasMore}}{{/vars}} {{/hasMore}}{{/vars}}
} }
{{#vars}}
{{#description}}# {{description}}{{/description}} {{#vars}}
self._{{name}} = None # {{{datatype}}} self._{{name}} = None{{#description}} # {{description}}{{/description}}
{{/vars}} {{/vars}}
{{#vars}}
{{#vars}}
@property @property
def {{name}}(self): def {{name}}(self):
return self._{{name}} return self._{{name}}
@ -54,18 +57,21 @@ class {{classname}}(object):
def {{name}}(self, {{name}}): def {{name}}(self, {{name}}):
{{#isEnum}}allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] {{#isEnum}}allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}]
if {{name}} not in allowed_values: if {{name}} not in allowed_values:
raise ValueError("Invalid value for `{{name}}`, must be one of {0}".format(allowed_values)) raise ValueError(
{{/isEnum}} "Invalid value for `{{name}}`, must be one of {0}"
self._{{name}} = {{name}} .format(allowed_values)
{{/vars}} )
{{/isEnum}}self._{{name}} = {{name}}
{{/vars}}
def __repr__(self): def __repr__(self):
properties = [] properties = []
for p in self.__dict__: for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap': 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}} {{/model}}
{{/models}} {{/models}}

View File

@ -51,6 +51,7 @@ class RESTResponse(io.IOBase):
""" """
return self.urllib3_response.getheader(name, default) return self.urllib3_response.getheader(name, default)
class RESTClientObject(object): class RESTClientObject(object):
def __init__(self, pools_size=4): def __init__(self, pools_size=4):
@ -87,14 +88,17 @@ class RESTClientObject(object):
:param query_params: query parameters in the url :param query_params: query parameters in the url
:param headers: http request headers :param headers: http request headers
:param body: request json body, for `application/json` :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` and `multipart/form-data`
""" """
method = method.upper() method = method.upper()
assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH'] assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH']
if post_params and body: 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 {} post_params = post_params or {}
headers = headers or {} headers = headers or {}
@ -144,22 +148,37 @@ class RESTClientObject(object):
return r return r
def GET(self, url, headers=None, query_params=None): 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): 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): 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): 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): 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): 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): class ApiException(Exception):
@ -190,6 +209,7 @@ class ApiException(Exception):
return error_message return error_message
class RESTClient(object): class RESTClient(object):
""" """
A class with all class methods to perform JSON requests. A class with all class methods to perform JSON requests.

View File

@ -27,415 +27,480 @@ from datetime import date
from six import iteritems from six import iteritems
try: try:
# for python3 # for python3
from urllib.parse import quote from urllib.parse import quote
except ImportError: except ImportError:
# for python2 # for python2
from urllib import quote from urllib import quote
from .configuration import Configuration from .configuration import Configuration
class ApiClient(object): 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 :param host: The base path for the server to call
:param header_name: a header to pass when making calls to the API
:return string: quoted value :param header_value: a header value to pass when making calls to the API
""" """
if type(obj) == list: def __init__(self, host=Configuration().host,
return ','.join(obj) header_name=None, header_value=None):
else:
return str(obj)
def sanitize_for_serialization(self, obj): self.default_headers = {}
""" if header_name is not None:
Sanitize an object for Request. 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. @property
If obj is str, int, float, bool, return directly. def user_agent(self):
If obj is datetime.datetime, datetime.date convert to string in iso8601 format. return self.default_headers['User-Agent']
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)}
def deserialize(self, response, response_type): @user_agent.setter
""" def user_agent(self, value):
Derialize response into an object. self.default_headers['User-Agent'] = value
:param response: RESTResponse object to be deserialized def set_default_header(self, header_name, header_value):
:param response_type: class literal for deserialzied object, or string of class name self.default_headers[header_name] = header_value
:return: deserialized object def __call_api(self, resource_path, method,
""" path_params=None, query_params=None, header_params=None,
# handle file downloading - save response body into a tmp file and return the instance body=None, post_params=None, files=None,
if "file" == response_type: response_type=None, auth_settings=None, callback=None):
return self.__deserialize_file(response)
# fetch data from response object # headers parameters
try: header_params = header_params or {}
data = json.loads(response.data) header_params.update(self.default_headers)
except ValueError: if self.cookie:
data = response.data 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): # query parameters
""" if query_params:
:param data: dict, list or str query_params = self.sanitize_for_serialization(query_params)
:param klass: class literal, or string of class name query_params = {k: self.to_path_value(v)
for k, v in iteritems(query_params)}
:return: object # post parameters
""" if post_params:
if data is None: post_params = self.prepare_post_parameters(post_params, files)
return None post_params = self.sanitize_for_serialization(post_params)
if type(klass) == str: # auth setting
if 'list[' in klass: self.update_params_for_auth(header_params, query_params, auth_settings)
sub_kls = re.match('list\[(.*)\]', klass).group(1)
return [self.__deserialize(sub_data, sub_kls) for sub_data in data]
if 'dict(' in klass: # body
sub_kls = re.match('dict\((.*), (.*)\)', klass).group(2) if body:
return {k: self.__deserialize(v, sub_kls) for k, v in iteritems(data)} body = self.sanitize_for_serialization(body)
# convert str to class # request url
# for native types url = self.host + resource_path
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]: # perform request and return response
return self.__deserialize_primitive(data, klass) response_data = self.request(method, url,
elif klass == object: query_params=query_params,
return self.__deserialize_object() headers=header_params,
elif klass == date: post_params=post_params, body=body)
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, self.last_response = response_data
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
# deserialize response data
:param resource_path: Path to method endpoint. if response_type:
:param method: Method to call. deserialized_data = self.deserialize(response_data, response_type)
: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']
else: else:
raise ValueError('Authentication token must be in `query` or `header`') deserialized_data = None
def __deserialize_file(self, response): if callback:
""" callback(deserialized_data)
Save response body into a file in (the defined) temporary folder, using the filename else:
from the `Content-Disposition` header if provided, otherwise a random filename. return deserialized_data
:param response: RESTResponse def to_path_value(self, obj):
:return: file path """
""" Convert a string or object to a path-friendly value
fd, path = tempfile.mkstemp(dir=configuration.temp_folder_path)
os.close(fd)
os.remove(path)
content_disposition = response.getheader("Content-Disposition") :param obj: object or string value
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: :return string: quoted value
f.write(response.data) """
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): If obj is None, return None.
""" If obj is str, int, float, bool, return directly.
Deserialize string to primitive type 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 return {key: self.sanitize_for_serialization(val)
:param klass: class literal for key, val in iteritems(obj_dict)}
:return: int, float, str, bool def deserialize(self, response, response_type):
""" """
try: Derialize response into an object.
value = klass(data)
except UnicodeEncodeError:
value = unicode(data)
except TypeError:
value = data
return value
def __deserialize_object(self): :param response: RESTResponse object to be deserialized
""" :param response_type: class literal for
Deserialize empty object deserialzied object, or string of class name
"""
return object()
def __deserialize_date(self, string): :return: deserialized object
""" """
Deserialize string to date # 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 # fetch data from response object
:return: date try:
""" data = json.loads(response.data)
try: except ValueError:
from dateutil.parser import parse data = response.data
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): return self.__deserialize(data, response_type)
"""
Deserialize string to datetime.
The string should be in iso8601 datetime format. def __deserialize(self, data, klass):
"""
:param data: dict, list or str
:param klass: class literal, or string of class name
:param string: str :return: object
:return: datetime """
""" if data is None:
try: return None
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): if type(klass) == str:
""" if 'list[' in klass:
Deserialize list or dict to model sub_kls = re.match('list\[(.*)\]', klass).group(1)
return [self.__deserialize(sub_data, sub_kls)
for sub_data in data]
:param data: dict, list if 'dict(' in klass:
:param klass: class literal sub_kls = re.match('dict\((.*), (.*)\)', klass).group(2)
""" return {k: self.__deserialize(v, sub_kls)
instance = klass() for k, v in iteritems(data)}
for attr, attr_type in iteritems(instance.swagger_types): # convert str to class
if data is not None \ # for native types
and instance.attribute_map[attr] in data\ if klass in ['int', 'float', 'str', 'bool',
and isinstance(data, (list, dict)): "date", 'datetime', "object"]:
value = data[instance.attribute_map[attr]] klass = eval(klass)
setattr(instance, attr, self.__deserialize(value, attr_type)) # for model types
else:
klass = eval('models.' + klass)
return instance 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

View File

@ -4,4 +4,3 @@ from __future__ import absolute_import
from .user_api import UserApi from .user_api import UserApi
from .pet_api import PetApi from .pet_api import PetApi
from .store_api import StoreApi from .store_api import StoreApi

View File

@ -17,7 +17,8 @@ Copyright 2015 SmartBear Software
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. 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 from __future__ import absolute_import
@ -30,6 +31,7 @@ from six import iteritems
from ..configuration import Configuration from ..configuration import Configuration
from ..api_client import ApiClient from ..api_client import ApiClient
class PetApi(object): class PetApi(object):
def __init__(self, api_client=None): def __init__(self, api_client=None):
@ -41,24 +43,25 @@ class PetApi(object):
config.api_client = ApiClient('http://petstore.swagger.io/v2') config.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = config.api_client self.api_client = config.api_client
def update_pet(self, **kwargs): def update_pet(self, **kwargs):
""" """
Update an existing pet 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.update_pet(callback=callback_function) >>> 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 :param Pet body: Pet object that needs to be added to the store
:return: None :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 = ['body']
@ -67,7 +70,10 @@ class PetApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -84,24 +90,32 @@ class PetApi(object):
files = {} files = {}
body_params = None body_params = None
if 'body' in params: if 'body' in params:
body_params = params['body'] body_params = params['body']
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = ['petstore_auth'] auth_settings = ['petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type=None, auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def add_pet(self, **kwargs): def add_pet(self, **kwargs):
@ -109,18 +123,20 @@ class PetApi(object):
Add a new pet to the store 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.add_pet(callback=callback_function) >>> 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 :param Pet body: Pet object that needs to be added to the store
:return: None :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 = ['body']
@ -129,7 +145,10 @@ class PetApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -146,24 +165,32 @@ class PetApi(object):
files = {} files = {}
body_params = None body_params = None
if 'body' in params: if 'body' in params:
body_params = params['body'] body_params = params['body']
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = ['petstore_auth'] auth_settings = ['petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type=None, auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def find_pets_by_status(self, **kwargs): def find_pets_by_status(self, **kwargs):
@ -171,18 +198,20 @@ class PetApi(object):
Finds Pets by status Finds Pets by status
Multiple status values can be provided with comma seperated strings 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.find_pets_by_status(callback=callback_function) >>> 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 :param list[str] status: Status values that need to be considered for filter
:return: list[Pet] :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 = ['status']
@ -191,7 +220,10 @@ class PetApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -201,7 +233,6 @@ class PetApi(object):
path_params = {} path_params = {}
query_params = {} query_params = {}
if 'status' in params: if 'status' in params:
query_params['status'] = params['status'] query_params['status'] = params['status']
@ -213,19 +244,28 @@ class PetApi(object):
body_params = None body_params = None
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = ['petstore_auth'] auth_settings = ['petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type='list[Pet]', auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def find_pets_by_tags(self, **kwargs): def find_pets_by_tags(self, **kwargs):
@ -233,18 +273,20 @@ class PetApi(object):
Finds Pets by tags Finds Pets by tags
Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.find_pets_by_tags(callback=callback_function) >>> 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 :param list[str] tags: Tags to filter by
:return: list[Pet] :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 = ['tags']
@ -253,7 +295,10 @@ class PetApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -263,7 +308,6 @@ class PetApi(object):
path_params = {} path_params = {}
query_params = {} query_params = {}
if 'tags' in params: if 'tags' in params:
query_params['tags'] = params['tags'] query_params['tags'] = params['tags']
@ -275,19 +319,28 @@ class PetApi(object):
body_params = None body_params = None
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = ['petstore_auth'] auth_settings = ['petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type='list[Pet]', auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def get_pet_by_id(self, pet_id, **kwargs): def get_pet_by_id(self, pet_id, **kwargs):
@ -295,18 +348,20 @@ class PetApi(object):
Find pet by ID Find pet by ID
Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.get_pet_by_id(pet_id, callback=callback_function) >>> 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) :param int pet_id: ID of pet that needs to be fetched (required)
:return: Pet :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 # verify the required parameter 'pet_id' is set
if pet_id is None: if pet_id is None:
@ -318,7 +373,10 @@ class PetApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -326,7 +384,6 @@ class PetApi(object):
method = 'GET' method = 'GET'
path_params = {} path_params = {}
if 'pet_id' in params: if 'pet_id' in params:
path_params['petId'] = params['pet_id'] path_params['petId'] = params['pet_id']
@ -340,19 +397,28 @@ class PetApi(object):
body_params = None body_params = None
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = ['api_key', 'petstore_auth'] auth_settings = ['api_key', 'petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type='Pet', auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def update_pet_with_form(self, pet_id, **kwargs): def update_pet_with_form(self, pet_id, **kwargs):
@ -360,20 +426,22 @@ class PetApi(object):
Updates a pet in the store with form data 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.update_pet_with_form(pet_id, callback=callback_function) >>> 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 pet_id: ID of pet that needs to be updated (required)
:param str name: Updated name of the pet :param str name: Updated name of the pet
:param str status: Updated status of the pet :param str status: Updated status of the pet
:return: None :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 # verify the required parameter 'pet_id' is set
if pet_id is None: if pet_id is None:
@ -385,7 +453,10 @@ class PetApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -393,7 +464,6 @@ class PetApi(object):
method = 'POST' method = 'POST'
path_params = {} path_params = {}
if 'pet_id' in params: if 'pet_id' in params:
path_params['petId'] = params['pet_id'] path_params['petId'] = params['pet_id']
@ -403,29 +473,36 @@ class PetApi(object):
form_params = {} form_params = {}
files = {} files = {}
if 'name' in params: if 'name' in params:
form_params['name'] = params['name'] form_params['name'] = params['name']
if 'status' in params: if 'status' in params:
form_params['status'] = params['status'] form_params['status'] = params['status']
body_params = None body_params = None
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = ['petstore_auth'] auth_settings = ['petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type=None, auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def delete_pet(self, pet_id, **kwargs): def delete_pet(self, pet_id, **kwargs):
@ -433,19 +510,21 @@ class PetApi(object):
Deletes a pet 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.delete_pet(pet_id, callback=callback_function) >>> 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 int pet_id: Pet id to delete (required)
:param str api_key: :param str api_key:
:return: None :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 # verify the required parameter 'pet_id' is set
if pet_id is None: if pet_id is None:
@ -457,7 +536,10 @@ class PetApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -465,14 +547,12 @@ class PetApi(object):
method = 'DELETE' method = 'DELETE'
path_params = {} path_params = {}
if 'pet_id' in params: if 'pet_id' in params:
path_params['petId'] = params['pet_id'] path_params['petId'] = params['pet_id']
query_params = {} query_params = {}
header_params = {} header_params = {}
if 'api_key' in params: if 'api_key' in params:
header_params['api_key'] = params['api_key'] header_params['api_key'] = params['api_key']
@ -482,19 +562,28 @@ class PetApi(object):
body_params = None body_params = None
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = ['petstore_auth'] auth_settings = ['petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type=None, auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def upload_file(self, pet_id, **kwargs): def upload_file(self, pet_id, **kwargs):
@ -502,20 +591,22 @@ class PetApi(object):
uploads an image 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.upload_file(pet_id, callback=callback_function) >>> 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 int pet_id: ID of pet to update (required)
:param str additional_metadata: Additional data to pass to server :param str additional_metadata: Additional data to pass to server
:param file file: file to upload :param file file: file to upload
:return: None :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 # verify the required parameter 'pet_id' is set
if pet_id is None: if pet_id is None:
@ -527,7 +618,10 @@ class PetApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -535,7 +629,6 @@ class PetApi(object):
method = 'POST' method = 'POST'
path_params = {} path_params = {}
if 'pet_id' in params: if 'pet_id' in params:
path_params['petId'] = params['pet_id'] path_params['petId'] = params['pet_id']
@ -545,28 +638,34 @@ class PetApi(object):
form_params = {} form_params = {}
files = {} files = {}
if 'additional_metadata' in params: if 'additional_metadata' in params:
form_params['additionalMetadata'] = params['additional_metadata'] form_params['additionalMetadata'] = params['additional_metadata']
if 'file' in params: if 'file' in params:
files['file'] = params['file'] files['file'] = params['file']
body_params = None body_params = None
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = ['petstore_auth'] auth_settings = ['petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type=None, auth_settings=auth_settings, callback=params.get('callback')) 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 return response

View File

@ -17,7 +17,8 @@ Copyright 2015 SmartBear Software
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. 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 from __future__ import absolute_import
@ -30,6 +31,7 @@ from six import iteritems
from ..configuration import Configuration from ..configuration import Configuration
from ..api_client import ApiClient from ..api_client import ApiClient
class StoreApi(object): class StoreApi(object):
def __init__(self, api_client=None): def __init__(self, api_client=None):
@ -41,23 +43,24 @@ class StoreApi(object):
config.api_client = ApiClient('http://petstore.swagger.io/v2') config.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = config.api_client self.api_client = config.api_client
def get_inventory(self, **kwargs): def get_inventory(self, **kwargs):
""" """
Returns pet inventories by status Returns pet inventories by status
Returns a map of status codes to quantities 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.get_inventory(callback=callback_function) >>> 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) :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 = []
@ -66,7 +69,10 @@ class StoreApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -85,19 +91,28 @@ class StoreApi(object):
body_params = None body_params = None
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = ['api_key'] auth_settings = ['api_key']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type='dict(str, int)', auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def place_order(self, **kwargs): def place_order(self, **kwargs):
@ -105,18 +120,20 @@ class StoreApi(object):
Place an order for a pet 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.place_order(callback=callback_function) >>> 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 :param Order body: order placed for purchasing the pet
:return: Order :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 = ['body']
@ -125,7 +142,10 @@ class StoreApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -142,24 +162,32 @@ class StoreApi(object):
files = {} files = {}
body_params = None body_params = None
if 'body' in params: if 'body' in params:
body_params = params['body'] body_params = params['body']
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type='Order', auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def get_order_by_id(self, order_id, **kwargs): def get_order_by_id(self, order_id, **kwargs):
@ -167,18 +195,20 @@ class StoreApi(object):
Find purchase order by ID Find purchase order by ID
For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.get_order_by_id(order_id, callback=callback_function) >>> 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) :param str order_id: ID of pet that needs to be fetched (required)
:return: Order :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 # verify the required parameter 'order_id' is set
if order_id is None: if order_id is None:
@ -190,7 +220,10 @@ class StoreApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -198,7 +231,6 @@ class StoreApi(object):
method = 'GET' method = 'GET'
path_params = {} path_params = {}
if 'order_id' in params: if 'order_id' in params:
path_params['orderId'] = params['order_id'] path_params['orderId'] = params['order_id']
@ -212,19 +244,28 @@ class StoreApi(object):
body_params = None body_params = None
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type='Order', auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def delete_order(self, order_id, **kwargs): def delete_order(self, order_id, **kwargs):
@ -232,18 +273,20 @@ class StoreApi(object):
Delete purchase order by ID Delete purchase order by ID
For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.delete_order(order_id, callback=callback_function) >>> 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) :param str order_id: ID of the order that needs to be deleted (required)
:return: None :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 # verify the required parameter 'order_id' is set
if order_id is None: if order_id is None:
@ -255,7 +298,10 @@ class StoreApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -263,7 +309,6 @@ class StoreApi(object):
method = 'DELETE' method = 'DELETE'
path_params = {} path_params = {}
if 'order_id' in params: if 'order_id' in params:
path_params['orderId'] = params['order_id'] path_params['orderId'] = params['order_id']
@ -277,18 +322,26 @@ class StoreApi(object):
body_params = None body_params = None
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type=None, auth_settings=auth_settings, callback=params.get('callback')) 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 return response

View File

@ -17,7 +17,8 @@ Copyright 2015 SmartBear Software
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. 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 from __future__ import absolute_import
@ -30,6 +31,7 @@ from six import iteritems
from ..configuration import Configuration from ..configuration import Configuration
from ..api_client import ApiClient from ..api_client import ApiClient
class UserApi(object): class UserApi(object):
def __init__(self, api_client=None): def __init__(self, api_client=None):
@ -41,24 +43,25 @@ class UserApi(object):
config.api_client = ApiClient('http://petstore.swagger.io/v2') config.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = config.api_client self.api_client = config.api_client
def create_user(self, **kwargs): def create_user(self, **kwargs):
""" """
Create user Create user
This can only be done by the logged in 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.create_user(callback=callback_function) >>> 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 :param User body: Created user object
:return: None :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 = ['body']
@ -67,7 +70,10 @@ class UserApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -84,24 +90,32 @@ class UserApi(object):
files = {} files = {}
body_params = None body_params = None
if 'body' in params: if 'body' in params:
body_params = params['body'] body_params = params['body']
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type=None, auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def create_users_with_array_input(self, **kwargs): def create_users_with_array_input(self, **kwargs):
@ -109,18 +123,20 @@ class UserApi(object):
Creates list of users with given input array 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.create_users_with_array_input(callback=callback_function) >>> 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 :param list[User] body: List of user object
:return: None :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 = ['body']
@ -129,7 +145,10 @@ class UserApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -146,24 +165,32 @@ class UserApi(object):
files = {} files = {}
body_params = None body_params = None
if 'body' in params: if 'body' in params:
body_params = params['body'] body_params = params['body']
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type=None, auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def create_users_with_list_input(self, **kwargs): def create_users_with_list_input(self, **kwargs):
@ -171,18 +198,20 @@ class UserApi(object):
Creates list of users with given input array 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.create_users_with_list_input(callback=callback_function) >>> 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 :param list[User] body: List of user object
:return: None :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 = ['body']
@ -191,7 +220,10 @@ class UserApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -208,24 +240,32 @@ class UserApi(object):
files = {} files = {}
body_params = None body_params = None
if 'body' in params: if 'body' in params:
body_params = params['body'] body_params = params['body']
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type=None, auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def login_user(self, **kwargs): def login_user(self, **kwargs):
@ -233,19 +273,21 @@ class UserApi(object):
Logs user into the system 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.login_user(callback=callback_function) >>> 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 username: The user name for login
:param str password: The password for login in clear text :param str password: The password for login in clear text
:return: str :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 = ['username', 'password']
@ -254,7 +296,10 @@ class UserApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -264,10 +309,8 @@ class UserApi(object):
path_params = {} path_params = {}
query_params = {} query_params = {}
if 'username' in params: if 'username' in params:
query_params['username'] = params['username'] query_params['username'] = params['username']
if 'password' in params: if 'password' in params:
query_params['password'] = params['password'] query_params['password'] = params['password']
@ -279,19 +322,28 @@ class UserApi(object):
body_params = None body_params = None
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type='str', auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def logout_user(self, **kwargs): def logout_user(self, **kwargs):
@ -299,17 +351,19 @@ class UserApi(object):
Logs out current logged in user session 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.logout_user(callback=callback_function) >>> 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 :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 = []
@ -318,7 +372,10 @@ class UserApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -337,19 +394,28 @@ class UserApi(object):
body_params = None body_params = None
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type=None, auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def get_user_by_name(self, username, **kwargs): def get_user_by_name(self, username, **kwargs):
@ -357,18 +423,20 @@ class UserApi(object):
Get user by user name 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.get_user_by_name(username, callback=callback_function) >>> 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) :param str username: The name that needs to be fetched. Use user1 for testing. (required)
:return: User :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 # verify the required parameter 'username' is set
if username is None: if username is None:
@ -380,7 +448,10 @@ class UserApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -388,7 +459,6 @@ class UserApi(object):
method = 'GET' method = 'GET'
path_params = {} path_params = {}
if 'username' in params: if 'username' in params:
path_params['username'] = params['username'] path_params['username'] = params['username']
@ -402,19 +472,28 @@ class UserApi(object):
body_params = None body_params = None
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type='User', auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def update_user(self, username, **kwargs): def update_user(self, username, **kwargs):
@ -422,19 +501,21 @@ class UserApi(object):
Updated user Updated user
This can only be done by the logged in 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.update_user(username, callback=callback_function) >>> 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 str username: name that need to be deleted (required)
:param User body: Updated user object :param User body: Updated user object
:return: None :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 # verify the required parameter 'username' is set
if username is None: if username is None:
@ -446,7 +527,10 @@ class UserApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -454,7 +538,6 @@ class UserApi(object):
method = 'PUT' method = 'PUT'
path_params = {} path_params = {}
if 'username' in params: if 'username' in params:
path_params['username'] = params['username'] path_params['username'] = params['username']
@ -466,24 +549,32 @@ class UserApi(object):
files = {} files = {}
body_params = None body_params = None
if 'body' in params: if 'body' in params:
body_params = params['body'] body_params = params['body']
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type=None, auth_settings=auth_settings, callback=params.get('callback')) 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 return response
def delete_user(self, username, **kwargs): def delete_user(self, username, **kwargs):
@ -491,18 +582,20 @@ class UserApi(object):
Delete user Delete user
This can only be done by the logged in 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: to be passed along and invoked when receiving response:
>>> def callback_function(response): >>> def callback_function(response):
>>> pprint(response) >>> pprint(response)
>>> >>>
>>> thread = api.delete_user(username, callback=callback_function) >>> 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) :param str username: The name that needs to be deleted (required)
:return: None :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 # verify the required parameter 'username' is set
if username is None: if username is None:
@ -514,7 +607,10 @@ class UserApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: 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 params[key] = val
del params['kwargs'] del params['kwargs']
@ -522,7 +618,6 @@ class UserApi(object):
method = 'DELETE' method = 'DELETE'
path_params = {} path_params = {}
if 'username' in params: if 'username' in params:
path_params['username'] = params['username'] path_params['username'] = params['username']
@ -536,18 +631,26 @@ class UserApi(object):
body_params = None body_params = None
# HTTP header `Accept` # 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']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # 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 # Authentication setting
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method,
body=body_params, post_params=form_params, files=files, path_params,
response_type=None, auth_settings=auth_settings, callback=params.get('callback')) 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 return response

View File

@ -5,6 +5,7 @@ import httplib
import sys import sys
import logging import logging
def singleton(cls, *args, **kw): def singleton(cls, *args, **kw):
instances = {} instances = {}
@ -23,6 +24,8 @@ class Configuration(object):
self.host = "http://petstore.swagger.io/v2" self.host = "http://petstore.swagger.io/v2"
# Default api client # Default api client
self.api_client = None self.api_client = None
# Temp file folder
self.temp_folder_path = None
# Authentication Settings # Authentication Settings
self.api_key = {} self.api_key = {}
self.api_key_prefix = {} self.api_key_prefix = {}
@ -94,21 +97,19 @@ class Configuration(object):
def auth_settings(self): def auth_settings(self):
""" Return Auth Settings for api client """ """ Return Auth Settings for api client """
return { return {
'api_key': { 'api_key':
'type': 'api_key', {
'in': 'header', 'type': 'api_key',
'key': 'api_key', 'in': 'header',
'value': self.get_api_key_with_prefix('api_key') 'key': 'api_key',
}, 'value': self.get_api_key_with_prefix('api_key')
},
} }
def to_debug_report(self): def to_debug_report(self):
return "Python SDK Debug Report:\n"\ return "Python SDK Debug Report:\n"\
"OS: {env}\n"\ "OS: {env}\n"\
"Python Version: {pyversion}\n"\ "Python Version: {pyversion}\n"\
"Version of the API: 1.0.0\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)

View File

@ -6,4 +6,3 @@ from .category import Category
from .pet import Pet from .pet import Pet
from .tag import Tag from .tag import Tag
from .order import Order from .order import Order

View File

@ -17,18 +17,20 @@ Copyright 2015 SmartBear Software
limitations under the License. limitations under the License.
""" """
class Category(object): class Category(object):
""" """
NOTE: This class is auto generated by the swagger code generator program. NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. Do not edit the class manually.
""" """
def __init__(self): def __init__(self):
""" """
Swagger model Swagger model
:param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict swaggerTypes: The key is attribute name
:param dict attributeMap: The key is attribute name and the value is json key in definition. 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 = { self.swagger_types = {
'id': 'int', 'id': 'int',
@ -40,12 +42,8 @@ class Category(object):
'name': 'name' 'name': 'name'
} }
self._id = None
self._id = None # int self._name = None
self._name = None # str
@property @property
def id(self): def id(self):
@ -53,7 +51,6 @@ class Category(object):
@id.setter @id.setter
def id(self, id): def id(self, id):
self._id = id self._id = id
@property @property
@ -62,15 +59,14 @@ class Category(object):
@name.setter @name.setter
def name(self, name): def name(self, name):
self._name = name self._name = name
def __repr__(self): def __repr__(self):
properties = [] properties = []
for p in self.__dict__: for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap': 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))

View File

@ -17,18 +17,20 @@ Copyright 2015 SmartBear Software
limitations under the License. limitations under the License.
""" """
class Order(object): class Order(object):
""" """
NOTE: This class is auto generated by the swagger code generator program. NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. Do not edit the class manually.
""" """
def __init__(self): def __init__(self):
""" """
Swagger model Swagger model
:param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict swaggerTypes: The key is attribute name
:param dict attributeMap: The key is attribute name and the value is json key in definition. 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 = { self.swagger_types = {
'id': 'int', 'id': 'int',
@ -48,24 +50,12 @@ class Order(object):
'complete': 'complete' 'complete': 'complete'
} }
self._id = None
self._id = None # int self._pet_id = None
self._quantity = None
self._ship_date = None
self._pet_id = None # int self._status = None # Order Status
self._complete = None
self._quantity = None # int
self._ship_date = None # datetime
# Order Status
self._status = None # str
self._complete = None # bool
@property @property
def id(self): def id(self):
@ -73,7 +63,6 @@ class Order(object):
@id.setter @id.setter
def id(self, id): def id(self, id):
self._id = id self._id = id
@property @property
@ -82,7 +71,6 @@ class Order(object):
@pet_id.setter @pet_id.setter
def pet_id(self, pet_id): def pet_id(self, pet_id):
self._pet_id = pet_id self._pet_id = pet_id
@property @property
@ -91,7 +79,6 @@ class Order(object):
@quantity.setter @quantity.setter
def quantity(self, quantity): def quantity(self, quantity):
self._quantity = quantity self._quantity = quantity
@property @property
@ -100,7 +87,6 @@ class Order(object):
@ship_date.setter @ship_date.setter
def ship_date(self, ship_date): def ship_date(self, ship_date):
self._ship_date = ship_date self._ship_date = ship_date
@property @property
@ -111,8 +97,10 @@ class Order(object):
def status(self, status): def status(self, status):
allowed_values = ["placed", "approved", "delivered"] allowed_values = ["placed", "approved", "delivered"]
if status not in allowed_values: 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 self._status = status
@property @property
@ -121,15 +109,14 @@ class Order(object):
@complete.setter @complete.setter
def complete(self, complete): def complete(self, complete):
self._complete = complete self._complete = complete
def __repr__(self): def __repr__(self):
properties = [] properties = []
for p in self.__dict__: for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap': 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))

View File

@ -17,18 +17,20 @@ Copyright 2015 SmartBear Software
limitations under the License. limitations under the License.
""" """
class Pet(object): class Pet(object):
""" """
NOTE: This class is auto generated by the swagger code generator program. NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. Do not edit the class manually.
""" """
def __init__(self): def __init__(self):
""" """
Swagger model Swagger model
:param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict swaggerTypes: The key is attribute name
:param dict attributeMap: The key is attribute name and the value is json key in definition. 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 = { self.swagger_types = {
'id': 'int', 'id': 'int',
@ -48,24 +50,12 @@ class Pet(object):
'status': 'status' 'status': 'status'
} }
self._id = None
self._id = None # int self._category = None
self._name = None
self._photo_urls = None
self._category = None # Category self._tags = None
self._status = None # pet status in the store
self._name = None # str
self._photo_urls = None # list[str]
self._tags = None # list[Tag]
# pet status in the store
self._status = None # str
@property @property
def id(self): def id(self):
@ -73,7 +63,6 @@ class Pet(object):
@id.setter @id.setter
def id(self, id): def id(self, id):
self._id = id self._id = id
@property @property
@ -82,7 +71,6 @@ class Pet(object):
@category.setter @category.setter
def category(self, category): def category(self, category):
self._category = category self._category = category
@property @property
@ -91,7 +79,6 @@ class Pet(object):
@name.setter @name.setter
def name(self, name): def name(self, name):
self._name = name self._name = name
@property @property
@ -100,7 +87,6 @@ class Pet(object):
@photo_urls.setter @photo_urls.setter
def photo_urls(self, photo_urls): def photo_urls(self, photo_urls):
self._photo_urls = photo_urls self._photo_urls = photo_urls
@property @property
@ -109,7 +95,6 @@ class Pet(object):
@tags.setter @tags.setter
def tags(self, tags): def tags(self, tags):
self._tags = tags self._tags = tags
@property @property
@ -120,16 +105,18 @@ class Pet(object):
def status(self, status): def status(self, status):
allowed_values = ["available", "pending", "sold"] allowed_values = ["available", "pending", "sold"]
if status not in allowed_values: 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 self._status = status
def __repr__(self): def __repr__(self):
properties = [] properties = []
for p in self.__dict__: for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap': 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))

View File

@ -17,18 +17,20 @@ Copyright 2015 SmartBear Software
limitations under the License. limitations under the License.
""" """
class Tag(object): class Tag(object):
""" """
NOTE: This class is auto generated by the swagger code generator program. NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. Do not edit the class manually.
""" """
def __init__(self): def __init__(self):
""" """
Swagger model Swagger model
:param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict swaggerTypes: The key is attribute name
:param dict attributeMap: The key is attribute name and the value is json key in definition. 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 = { self.swagger_types = {
'id': 'int', 'id': 'int',
@ -40,12 +42,8 @@ class Tag(object):
'name': 'name' 'name': 'name'
} }
self._id = None
self._id = None # int self._name = None
self._name = None # str
@property @property
def id(self): def id(self):
@ -53,7 +51,6 @@ class Tag(object):
@id.setter @id.setter
def id(self, id): def id(self, id):
self._id = id self._id = id
@property @property
@ -62,15 +59,14 @@ class Tag(object):
@name.setter @name.setter
def name(self, name): def name(self, name):
self._name = name self._name = name
def __repr__(self): def __repr__(self):
properties = [] properties = []
for p in self.__dict__: for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap': 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))

View File

@ -17,18 +17,20 @@ Copyright 2015 SmartBear Software
limitations under the License. limitations under the License.
""" """
class User(object): class User(object):
""" """
NOTE: This class is auto generated by the swagger code generator program. NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. Do not edit the class manually.
""" """
def __init__(self): def __init__(self):
""" """
Swagger model Swagger model
:param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict swaggerTypes: The key is attribute name
:param dict attributeMap: The key is attribute name and the value is json key in definition. 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 = { self.swagger_types = {
'id': 'int', 'id': 'int',
@ -52,30 +54,14 @@ class User(object):
'user_status': 'userStatus' 'user_status': 'userStatus'
} }
self._id = None
self._id = None # int self._username = None
self._first_name = None
self._last_name = None
self._username = None # str self._email = None
self._password = None
self._phone = None
self._first_name = None # str self._user_status = None # User Status
self._last_name = None # str
self._email = None # str
self._password = None # str
self._phone = None # str
# User Status
self._user_status = None # int
@property @property
def id(self): def id(self):
@ -83,7 +69,6 @@ class User(object):
@id.setter @id.setter
def id(self, id): def id(self, id):
self._id = id self._id = id
@property @property
@ -92,7 +77,6 @@ class User(object):
@username.setter @username.setter
def username(self, username): def username(self, username):
self._username = username self._username = username
@property @property
@ -101,7 +85,6 @@ class User(object):
@first_name.setter @first_name.setter
def first_name(self, first_name): def first_name(self, first_name):
self._first_name = first_name self._first_name = first_name
@property @property
@ -110,7 +93,6 @@ class User(object):
@last_name.setter @last_name.setter
def last_name(self, last_name): def last_name(self, last_name):
self._last_name = last_name self._last_name = last_name
@property @property
@ -119,7 +101,6 @@ class User(object):
@email.setter @email.setter
def email(self, email): def email(self, email):
self._email = email self._email = email
@property @property
@ -128,7 +109,6 @@ class User(object):
@password.setter @password.setter
def password(self, password): def password(self, password):
self._password = password self._password = password
@property @property
@ -137,7 +117,6 @@ class User(object):
@phone.setter @phone.setter
def phone(self, phone): def phone(self, phone):
self._phone = phone self._phone = phone
@property @property
@ -146,15 +125,14 @@ class User(object):
@user_status.setter @user_status.setter
def user_status(self, user_status): def user_status(self, user_status):
self._user_status = user_status self._user_status = user_status
def __repr__(self): def __repr__(self):
properties = [] properties = []
for p in self.__dict__: for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap': 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))

View File

@ -51,6 +51,7 @@ class RESTResponse(io.IOBase):
""" """
return self.urllib3_response.getheader(name, default) return self.urllib3_response.getheader(name, default)
class RESTClientObject(object): class RESTClientObject(object):
def __init__(self, pools_size=4): def __init__(self, pools_size=4):
@ -87,14 +88,17 @@ class RESTClientObject(object):
:param query_params: query parameters in the url :param query_params: query parameters in the url
:param headers: http request headers :param headers: http request headers
:param body: request json body, for `application/json` :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` and `multipart/form-data`
""" """
method = method.upper() method = method.upper()
assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH'] assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH']
if post_params and body: 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 {} post_params = post_params or {}
headers = headers or {} headers = headers or {}
@ -144,22 +148,37 @@ class RESTClientObject(object):
return r return r
def GET(self, url, headers=None, query_params=None): 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): 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): 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): 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): 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): 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): class ApiException(Exception):
@ -190,6 +209,7 @@ class ApiException(Exception):
return error_message return error_message
class RESTClient(object): class RESTClient(object):
""" """
A class with all class methods to perform JSON requests. A class with all class methods to perform JSON requests.