forked from loafle/openapi-generator-original
rollback python template
This commit is contained in:
parent
915ad77d03
commit
0dd8670724
@ -67,8 +67,8 @@ If you want to run the tests in all the python platforms:
|
|||||||
```sh
|
```sh
|
||||||
$ make test-all
|
$ make test-all
|
||||||
[... tox creates a virtualenv for every platform and runs tests inside of each]
|
[... tox creates a virtualenv for every platform and runs tests inside of each]
|
||||||
py27: commands succeeded
|
py27: commands succeeded
|
||||||
py34: commands succeeded
|
py34: commands succeeded
|
||||||
congratulations :)
|
congratulations :)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -5,17 +5,17 @@
|
|||||||
{{classname}}.py
|
{{classname}}.py
|
||||||
Copyright 2015 SmartBear Software
|
Copyright 2015 SmartBear Software
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
You may obtain a copy of the License at
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
Unless required by applicable law or agreed to in writing, software
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
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.
|
||||||
"""
|
"""
|
||||||
@ -31,18 +31,18 @@ from .. import configuration
|
|||||||
from ..api_client import ApiClient
|
from ..api_client import ApiClient
|
||||||
|
|
||||||
{{#operations}}
|
{{#operations}}
|
||||||
class {{classname}}(object):
|
class {{classname}}(object):
|
||||||
|
|
||||||
def __init__(self, api_client=None):
|
def __init__(self, api_client=None):
|
||||||
if api_client:
|
if api_client:
|
||||||
self.api_client = api_client
|
self.api_client = api_client
|
||||||
else:
|
else:
|
||||||
if not configuration.api_client:
|
if not configuration.api_client:
|
||||||
configuration.api_client = ApiClient('{{basePath}}')
|
configuration.api_client = ApiClient('{{basePath}}')
|
||||||
self.api_client = configuration.api_client
|
self.api_client = configuration.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}}}
|
||||||
@ -52,17 +52,17 @@ from ..api_client import ApiClient
|
|||||||
:return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}}
|
:return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}}
|
||||||
"""
|
"""
|
||||||
{{#allParams}}{{#required}}
|
{{#allParams}}{{#required}}
|
||||||
# verify the required parameter '{{paramName}}' is set
|
# 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}}]
|
||||||
|
|
||||||
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']
|
||||||
|
|
||||||
resource_path = '{{path}}'.replace('{format}', 'json')
|
resource_path = '{{path}}'.replace('{format}', 'json')
|
||||||
@ -70,34 +70,34 @@ from ..api_client import ApiClient
|
|||||||
|
|
||||||
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}}])
|
||||||
@ -106,10 +106,10 @@ from ..api_client import ApiClient
|
|||||||
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, path_params, query_params, header_params,
|
||||||
body=body_params, post_params=form_params, files=files,
|
body=body_params, post_params=form_params, files=files,
|
||||||
response={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, auth_settings=auth_settings)
|
response={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, auth_settings=auth_settings)
|
||||||
{{#returnType}}
|
{{#returnType}}
|
||||||
return response
|
return response
|
||||||
{{/returnType}}{{/operation}}
|
{{/returnType}}{{/operation}}
|
||||||
{{/operations}}
|
{{/operations}}
|
||||||
|
|
||||||
|
@ -22,282 +22,282 @@ import random
|
|||||||
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 . import configuration
|
from . import configuration
|
||||||
|
|
||||||
class ApiClient(object):
|
class ApiClient(object):
|
||||||
"""
|
"""
|
||||||
Generic API client for Swagger client library builds
|
Generic API client for Swagger client library builds
|
||||||
|
|
||||||
:param host: The base path for the server to call
|
: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_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
|
: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):
|
def __init__(self, host=configuration.host, header_name=None, header_value=None):
|
||||||
self.default_headers = {}
|
self.default_headers = {}
|
||||||
if header_name is not None:
|
if header_name is not None:
|
||||||
self.default_headers[header_name] = header_value
|
self.default_headers[header_name] = header_value
|
||||||
self.host = host
|
self.host = host
|
||||||
self.cookie = None
|
self.cookie = None
|
||||||
# Set default User-Agent.
|
# Set default User-Agent.
|
||||||
self.user_agent = 'Python-Swagger'
|
self.user_agent = 'Python-Swagger'
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def user_agent(self):
|
def user_agent(self):
|
||||||
return self.default_headers['User-Agent']
|
return self.default_headers['User-Agent']
|
||||||
|
|
||||||
@user_agent.setter
|
@user_agent.setter
|
||||||
def user_agent(self, value):
|
def user_agent(self, value):
|
||||||
self.default_headers['User-Agent'] = value
|
self.default_headers['User-Agent'] = value
|
||||||
|
|
||||||
def set_default_header(self, header_name, header_value):
|
def set_default_header(self, header_name, header_value):
|
||||||
self.default_headers[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,
|
def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None,
|
||||||
body=None, post_params=None, files=None, response=None, auth_settings=None):
|
body=None, post_params=None, files=None, response=None, auth_settings=None):
|
||||||
|
|
||||||
# headers parameters
|
# headers parameters
|
||||||
header_params = header_params or {}
|
header_params = header_params or {}
|
||||||
header_params.update(self.default_headers)
|
header_params.update(self.default_headers)
|
||||||
if self.cookie:
|
if self.cookie:
|
||||||
header_params['Cookie'] = self.cookie
|
header_params['Cookie'] = self.cookie
|
||||||
if header_params:
|
if header_params:
|
||||||
header_params = self.sanitize_for_serialization(header_params)
|
header_params = self.sanitize_for_serialization(header_params)
|
||||||
|
|
||||||
# path parameters
|
# path parameters
|
||||||
if path_params:
|
if path_params:
|
||||||
path_params = self.sanitize_for_serialization(path_params)
|
path_params = self.sanitize_for_serialization(path_params)
|
||||||
for k, v in iteritems(path_params):
|
for k, v in iteritems(path_params):
|
||||||
replacement = quote(str(self.to_path_value(v)))
|
replacement = quote(str(self.to_path_value(v)))
|
||||||
resource_path = resource_path.replace('{' + k + '}', replacement)
|
resource_path = resource_path.replace('{' + k + '}', replacement)
|
||||||
|
|
||||||
# query parameters
|
# query parameters
|
||||||
if query_params:
|
if query_params:
|
||||||
query_params = self.sanitize_for_serialization(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)}
|
query_params = {k: self.to_path_value(v) for k, v in iteritems(query_params)}
|
||||||
|
|
||||||
# post parameters
|
# post parameters
|
||||||
if post_params:
|
if post_params:
|
||||||
post_params = self.prepare_post_parameters(post_params, files)
|
post_params = self.prepare_post_parameters(post_params, files)
|
||||||
post_params = self.sanitize_for_serialization(post_params)
|
post_params = self.sanitize_for_serialization(post_params)
|
||||||
|
|
||||||
# auth setting
|
# auth setting
|
||||||
self.update_params_for_auth(header_params, query_params, auth_settings)
|
self.update_params_for_auth(header_params, query_params, auth_settings)
|
||||||
|
|
||||||
# body
|
# body
|
||||||
if body:
|
if body:
|
||||||
body = self.sanitize_for_serialization(body)
|
body = self.sanitize_for_serialization(body)
|
||||||
|
|
||||||
# request url
|
# request url
|
||||||
url = self.host + resource_path
|
url = self.host + resource_path
|
||||||
|
|
||||||
# perform request and return response
|
# perform request and return response
|
||||||
response_data = self.request(method, url, query_params=query_params, headers=header_params,
|
response_data = self.request(method, url, query_params=query_params, headers=header_params,
|
||||||
post_params=post_params, body=body)
|
post_params=post_params, body=body)
|
||||||
|
|
||||||
# deserialize response data
|
# deserialize response data
|
||||||
if response:
|
if response:
|
||||||
return self.deserialize(response_data, response)
|
return self.deserialize(response_data, response)
|
||||||
else:
|
else:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def to_path_value(self, obj):
|
def to_path_value(self, obj):
|
||||||
"""
|
"""
|
||||||
Convert a string or object to a path-friendly value
|
Convert a string or object to a path-friendly value
|
||||||
|
|
||||||
:param obj: object or string value
|
:param obj: object or string value
|
||||||
|
|
||||||
:return string: quoted value
|
:return string: quoted value
|
||||||
"""
|
"""
|
||||||
if type(obj) == list:
|
if type(obj) == list:
|
||||||
return ','.join(obj)
|
return ','.join(obj)
|
||||||
else:
|
else:
|
||||||
return str(obj)
|
return str(obj)
|
||||||
|
|
||||||
def sanitize_for_serialization(self, obj):
|
def sanitize_for_serialization(self, obj):
|
||||||
"""
|
"""
|
||||||
Sanitize an object for Request.
|
Sanitize an object for Request.
|
||||||
|
|
||||||
If obj is None, return None.
|
If obj is None, return None.
|
||||||
If obj is str, int, float, bool, return directly.
|
If obj is str, int, float, bool, return directly.
|
||||||
If obj is datetime.datetime, datetime.date convert to string in iso8601 format.
|
If obj is datetime.datetime, datetime.date convert to string in iso8601 format.
|
||||||
If obj is list, santize each element in the list.
|
If obj is list, santize each element in the list.
|
||||||
If obj is dict, return the dict.
|
If obj is dict, return the dict.
|
||||||
If obj is swagger model, return the properties dict.
|
If obj is swagger model, return the properties dict.
|
||||||
"""
|
"""
|
||||||
if isinstance(obj, type(None)):
|
if isinstance(obj, type(None)):
|
||||||
return None
|
return None
|
||||||
elif isinstance(obj, (str, int, float, bool, tuple)):
|
elif isinstance(obj, (str, int, float, bool, tuple)):
|
||||||
return obj
|
return obj
|
||||||
elif isinstance(obj, list):
|
elif isinstance(obj, list):
|
||||||
return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj]
|
return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj]
|
||||||
elif isinstance(obj, (datetime.datetime, datetime.date)):
|
elif isinstance(obj, (datetime.datetime, datetime.date)):
|
||||||
return obj.isoformat()
|
return obj.isoformat()
|
||||||
else:
|
else:
|
||||||
if isinstance(obj, dict):
|
if isinstance(obj, dict):
|
||||||
obj_dict = obj
|
obj_dict = obj
|
||||||
else:
|
else:
|
||||||
# Convert model obj to dict except attributes `swagger_types`, `attribute_map`
|
# Convert model obj to dict except attributes `swagger_types`, `attribute_map`
|
||||||
# and attributes which value is not None.
|
# and attributes which value is not None.
|
||||||
# Convert attribute name to json key in model definition for request.
|
# Convert attribute name to json key in model definition for request.
|
||||||
obj_dict = {obj.attribute_map[key]: val
|
obj_dict = {obj.attribute_map[key]: val
|
||||||
for key, val in iteritems(obj.__dict__)
|
for key, val in iteritems(obj.__dict__)
|
||||||
if key != 'swagger_types' and key != 'attribute_map' and val is not None}
|
if key != 'swagger_types' and key != 'attribute_map' and val is not None}
|
||||||
return {key: self.sanitize_for_serialization(val)
|
return {key: self.sanitize_for_serialization(val)
|
||||||
for key, val in iteritems(obj_dict)}
|
for key, val in iteritems(obj_dict)}
|
||||||
|
|
||||||
def deserialize(self, obj, obj_class):
|
def deserialize(self, obj, obj_class):
|
||||||
"""
|
"""
|
||||||
Derialize a JSON string into an object.
|
Derialize a JSON string into an object.
|
||||||
|
|
||||||
:param obj: string or object to be deserialized
|
:param obj: string or object to be deserialized
|
||||||
:param obj_class: class literal for deserialzied object, or string of class name
|
:param obj_class: class literal for deserialzied object, or string of class name
|
||||||
|
|
||||||
:return object: deserialized object
|
:return object: deserialized object
|
||||||
"""
|
"""
|
||||||
# Have to accept obj_class as string or actual type. Type could be a
|
# Have to accept obj_class as string or actual type. Type could be a
|
||||||
# native Python type, or one of the model classes.
|
# native Python type, or one of the model classes.
|
||||||
if type(obj_class) == str:
|
if type(obj_class) == str:
|
||||||
if 'list[' in obj_class:
|
if 'list[' in obj_class:
|
||||||
match = re.match('list\[(.*)\]', obj_class)
|
match = re.match('list\[(.*)\]', obj_class)
|
||||||
sub_class = match.group(1)
|
sub_class = match.group(1)
|
||||||
return [self.deserialize(sub_obj, sub_class) for sub_obj in obj]
|
return [self.deserialize(sub_obj, sub_class) for sub_obj in obj]
|
||||||
|
|
||||||
if obj_class in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']:
|
if obj_class in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']:
|
||||||
obj_class = eval(obj_class)
|
obj_class = eval(obj_class)
|
||||||
else: # not a native type, must be model class
|
else: # not a native type, must be model class
|
||||||
obj_class = eval('models.' + obj_class)
|
obj_class = eval('models.' + obj_class)
|
||||||
|
|
||||||
if obj_class in [int, float, dict, list, str, bool]:
|
if obj_class in [int, float, dict, list, str, bool]:
|
||||||
return obj_class(obj)
|
return obj_class(obj)
|
||||||
elif obj_class == datetime:
|
elif obj_class == datetime:
|
||||||
return self.__parse_string_to_datetime(obj)
|
return self.__parse_string_to_datetime(obj)
|
||||||
|
|
||||||
instance = obj_class()
|
instance = obj_class()
|
||||||
|
|
||||||
for attr, attr_type in iteritems(instance.swagger_types):
|
for attr, attr_type in iteritems(instance.swagger_types):
|
||||||
if obj is not None and instance.attribute_map[attr] in obj and type(obj) in [list, dict]:
|
if obj is not None and instance.attribute_map[attr] in obj and type(obj) in [list, dict]:
|
||||||
value = obj[instance.attribute_map[attr]]
|
value = obj[instance.attribute_map[attr]]
|
||||||
if attr_type in ['str', 'int', 'float', 'bool']:
|
if attr_type in ['str', 'int', 'float', 'bool']:
|
||||||
attr_type = eval(attr_type)
|
attr_type = eval(attr_type)
|
||||||
try:
|
try:
|
||||||
value = attr_type(value)
|
value = attr_type(value)
|
||||||
except UnicodeEncodeError:
|
except UnicodeEncodeError:
|
||||||
value = unicode(value)
|
value = unicode(value)
|
||||||
except TypeError:
|
except TypeError:
|
||||||
value = value
|
value = value
|
||||||
setattr(instance, attr, value)
|
setattr(instance, attr, value)
|
||||||
elif attr_type == 'datetime':
|
elif attr_type == 'datetime':
|
||||||
setattr(instance, attr, self.__parse_string_to_datetime(value))
|
setattr(instance, attr, self.__parse_string_to_datetime(value))
|
||||||
elif 'list[' in attr_type:
|
elif 'list[' in attr_type:
|
||||||
match = re.match('list\[(.*)\]', attr_type)
|
match = re.match('list\[(.*)\]', attr_type)
|
||||||
sub_class = match.group(1)
|
sub_class = match.group(1)
|
||||||
sub_values = []
|
sub_values = []
|
||||||
if not value:
|
if not value:
|
||||||
setattr(instance, attr, None)
|
setattr(instance, attr, None)
|
||||||
else:
|
else:
|
||||||
for sub_value in value:
|
for sub_value in value:
|
||||||
sub_values.append(self.deserialize(sub_value, sub_class))
|
sub_values.append(self.deserialize(sub_value, sub_class))
|
||||||
setattr(instance, attr, sub_values)
|
setattr(instance, attr, sub_values)
|
||||||
else:
|
else:
|
||||||
setattr(instance, attr, self.deserialize(value, attr_type))
|
setattr(instance, attr, self.deserialize(value, attr_type))
|
||||||
|
|
||||||
return instance
|
return instance
|
||||||
|
|
||||||
def __parse_string_to_datetime(self, string):
|
def __parse_string_to_datetime(self, string):
|
||||||
"""
|
"""
|
||||||
Parse datetime in string to datetime.
|
Parse datetime in string to datetime.
|
||||||
|
|
||||||
The string should be in iso8601 datetime format.
|
The string should be in iso8601 datetime format.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
from dateutil.parser import parse
|
from dateutil.parser import parse
|
||||||
return parse(string)
|
return parse(string)
|
||||||
except ImportError:
|
except ImportError:
|
||||||
return string
|
return string
|
||||||
|
|
||||||
def request(self, method, url, query_params=None, headers=None, post_params=None, body=None):
|
def request(self, method, url, query_params=None, headers=None, post_params=None, body=None):
|
||||||
"""
|
"""
|
||||||
Perform http request using RESTClient.
|
Perform http request using RESTClient.
|
||||||
"""
|
"""
|
||||||
if method == "GET":
|
if method == "GET":
|
||||||
return RESTClient.GET(url, query_params=query_params, headers=headers)
|
return RESTClient.GET(url, query_params=query_params, headers=headers)
|
||||||
elif method == "HEAD":
|
elif method == "HEAD":
|
||||||
return RESTClient.HEAD(url, query_params=query_params, headers=headers)
|
return RESTClient.HEAD(url, query_params=query_params, headers=headers)
|
||||||
elif method == "POST":
|
elif method == "POST":
|
||||||
return RESTClient.POST(url, headers=headers, post_params=post_params, body=body)
|
return RESTClient.POST(url, headers=headers, post_params=post_params, body=body)
|
||||||
elif method == "PUT":
|
elif method == "PUT":
|
||||||
return RESTClient.PUT(url, headers=headers, post_params=post_params, body=body)
|
return RESTClient.PUT(url, headers=headers, post_params=post_params, body=body)
|
||||||
elif method == "PATCH":
|
elif method == "PATCH":
|
||||||
return RESTClient.PATCH(url, headers=headers, post_params=post_params, body=body)
|
return RESTClient.PATCH(url, headers=headers, post_params=post_params, body=body)
|
||||||
elif method == "DELETE":
|
elif method == "DELETE":
|
||||||
return RESTClient.DELETE(url, query_params=query_params, headers=headers)
|
return RESTClient.DELETE(url, query_params=query_params, headers=headers)
|
||||||
else:
|
else:
|
||||||
raise ValueError("http method must be `GET`, `HEAD`, `POST`, `PATCH`, `PUT` or `DELETE`")
|
raise ValueError("http method must be `GET`, `HEAD`, `POST`, `PATCH`, `PUT` or `DELETE`")
|
||||||
|
|
||||||
def prepare_post_parameters(self, post_params=None, files=None):
|
def prepare_post_parameters(self, post_params=None, files=None):
|
||||||
params = {}
|
params = {}
|
||||||
|
|
||||||
if post_params:
|
if post_params:
|
||||||
params.update(post_params)
|
params.update(post_params)
|
||||||
|
|
||||||
if files:
|
if files:
|
||||||
for k, v in iteritems(files):
|
for k, v in iteritems(files):
|
||||||
if v:
|
if v:
|
||||||
with open(v, 'rb') as f:
|
with open(v, 'rb') as f:
|
||||||
filename = os.path.basename(f.name)
|
filename = os.path.basename(f.name)
|
||||||
filedata = f.read()
|
filedata = f.read()
|
||||||
mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
|
mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
|
||||||
params[k] = tuple([filename, filedata, mimetype])
|
params[k] = tuple([filename, filedata, mimetype])
|
||||||
|
|
||||||
return params
|
return params
|
||||||
|
|
||||||
def select_header_accept(self, accepts):
|
def select_header_accept(self, accepts):
|
||||||
"""
|
"""
|
||||||
Return `Accept` based on an array of accepts provided
|
Return `Accept` based on an array of accepts provided
|
||||||
"""
|
"""
|
||||||
if not accepts:
|
if not accepts:
|
||||||
return
|
return
|
||||||
|
|
||||||
accepts = list(map(lambda x: x.lower(), accepts))
|
accepts = list(map(lambda x: x.lower(), accepts))
|
||||||
|
|
||||||
if 'application/json' in accepts:
|
if 'application/json' in accepts:
|
||||||
return 'application/json'
|
return 'application/json'
|
||||||
else:
|
else:
|
||||||
return ', '.join(accepts)
|
return ', '.join(accepts)
|
||||||
|
|
||||||
def select_header_content_type(self, content_types):
|
def select_header_content_type(self, content_types):
|
||||||
"""
|
"""
|
||||||
Return `Content-Type` baseed on an array of content_types provided
|
Return `Content-Type` baseed on an array of content_types provided
|
||||||
"""
|
"""
|
||||||
if not content_types:
|
if not content_types:
|
||||||
return 'application/json'
|
return 'application/json'
|
||||||
|
|
||||||
content_types = list(map(lambda x: x.lower(), content_types))
|
content_types = list(map(lambda x: x.lower(), content_types))
|
||||||
|
|
||||||
if 'application/json' in content_types:
|
if 'application/json' in content_types:
|
||||||
return 'application/json'
|
return 'application/json'
|
||||||
else:
|
else:
|
||||||
return content_types[0]
|
return content_types[0]
|
||||||
|
|
||||||
def update_params_for_auth(self, headers, querys, auth_settings):
|
def update_params_for_auth(self, headers, querys, auth_settings):
|
||||||
"""
|
"""
|
||||||
Update header and query params based on authentication setting
|
Update header and query params based on authentication setting
|
||||||
"""
|
"""
|
||||||
if not auth_settings:
|
if not auth_settings:
|
||||||
return
|
return
|
||||||
|
|
||||||
for auth in auth_settings:
|
for auth in auth_settings:
|
||||||
auth_setting = configuration.auth_settings().get(auth)
|
auth_setting = configuration.auth_settings().get(auth)
|
||||||
if auth_setting:
|
if auth_setting:
|
||||||
if auth_setting['in'] == 'header':
|
if auth_setting['in'] == 'header':
|
||||||
headers[auth_setting['key']] = auth_setting['value']
|
headers[auth_setting['key']] = auth_setting['value']
|
||||||
elif auth_setting['in'] == 'query':
|
elif auth_setting['in'] == 'query':
|
||||||
querys[auth_setting['key']] = auth_setting['value']
|
querys[auth_setting['key']] = auth_setting['value']
|
||||||
else:
|
else:
|
||||||
raise ValueError('Authentication token must be in `query` or `header`')
|
raise ValueError('Authentication token must be in `query` or `header`')
|
||||||
|
@ -3,44 +3,44 @@ import base64
|
|||||||
import urllib3
|
import urllib3
|
||||||
|
|
||||||
def get_api_key_with_prefix(key):
|
def get_api_key_with_prefix(key):
|
||||||
global api_key
|
global api_key
|
||||||
global api_key_prefix
|
global api_key_prefix
|
||||||
|
|
||||||
if api_key.get(key) and api_key_prefix.get(key):
|
if api_key.get(key) and api_key_prefix.get(key):
|
||||||
return api_key_prefix[key] + ' ' + api_key[key]
|
return api_key_prefix[key] + ' ' + api_key[key]
|
||||||
elif api_key.get(key):
|
elif api_key.get(key):
|
||||||
return api_key[key]
|
return api_key[key]
|
||||||
|
|
||||||
def get_basic_auth_token():
|
def get_basic_auth_token():
|
||||||
global username
|
global username
|
||||||
global password
|
global password
|
||||||
|
|
||||||
return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization')
|
return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization')
|
||||||
|
|
||||||
def auth_settings():
|
def auth_settings():
|
||||||
return { {{#authMethods}}{{#isApiKey}}
|
return { {{#authMethods}}{{#isApiKey}}
|
||||||
'{{name}}': {
|
'{{name}}': {
|
||||||
'type': 'api_key',
|
'type': 'api_key',
|
||||||
'in': {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}},
|
'in': {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}},
|
||||||
'key': '{{keyParamName}}',
|
'key': '{{keyParamName}}',
|
||||||
'value': get_api_key_with_prefix('{{keyParamName}}')
|
'value': get_api_key_with_prefix('{{keyParamName}}')
|
||||||
},
|
},
|
||||||
{{/isApiKey}}{{#isBasic}}
|
{{/isApiKey}}{{#isBasic}}
|
||||||
'{{name}}': {
|
'{{name}}': {
|
||||||
'type': 'basic',
|
'type': 'basic',
|
||||||
'in': 'header',
|
'in': 'header',
|
||||||
'key': 'Authorization',
|
'key': 'Authorization',
|
||||||
'value': get_basic_auth_token()
|
'value': get_basic_auth_token()
|
||||||
},
|
},
|
||||||
{{/isBasic}}{{/authMethods}}
|
{{/isBasic}}{{/authMethods}}
|
||||||
}
|
}
|
||||||
|
|
||||||
# Default Base url
|
# Default Base url
|
||||||
host = "{{basePath}}"
|
host = "{{basePath}}"
|
||||||
|
|
||||||
# Default api client
|
# Default api client
|
||||||
api_client = None
|
api_client = None
|
||||||
|
|
||||||
# Authentication settings
|
# Authentication settings
|
||||||
|
|
||||||
api_key = {}
|
api_key = {}
|
||||||
|
@ -4,28 +4,28 @@
|
|||||||
"""
|
"""
|
||||||
Copyright 2015 SmartBear Software
|
Copyright 2015 SmartBear Software
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
You may obtain a copy of the License at
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
Unless required by applicable law or agreed to in writing, software
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
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.
|
||||||
"""
|
"""
|
||||||
{{#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
|
||||||
|
|
||||||
@ -33,27 +33,27 @@ limitations under the License.
|
|||||||
:param dict attributeMap: The key is attribute name and the value is json key in definition.
|
: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}},
|
||||||
{{/hasMore}}{{/vars}}
|
{{/hasMore}}{{/vars}}
|
||||||
}
|
}
|
||||||
|
|
||||||
self.attribute_map = {
|
self.attribute_map = {
|
||||||
{{#vars}}'{{name}}': '{{baseName}}'{{#hasMore}},
|
{{#vars}}'{{name}}': '{{baseName}}'{{#hasMore}},
|
||||||
{{/hasMore}}{{/vars}}
|
{{/hasMore}}{{/vars}}
|
||||||
}
|
}
|
||||||
{{#vars}}
|
{{#vars}}
|
||||||
{{#description}}# {{description}}{{/description}}
|
{{#description}}# {{description}}{{/description}}
|
||||||
self.{{name}} = None # {{{datatype}}}
|
self.{{name}} = None # {{{datatype}}}
|
||||||
{{/vars}}
|
{{/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}}
|
||||||
|
|
||||||
|
|
||||||
|
@ -15,239 +15,239 @@ import certifi
|
|||||||
from six import iteritems
|
from six import iteritems
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import urllib3
|
import urllib3
|
||||||
except ImportError:
|
except ImportError:
|
||||||
raise ImportError('Swagger python client requires urllib3.')
|
raise ImportError('Swagger python client requires urllib3.')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# for python3
|
# for python3
|
||||||
from urllib.parse import urlencode
|
from urllib.parse import urlencode
|
||||||
except ImportError:
|
except ImportError:
|
||||||
# for python2
|
# for python2
|
||||||
from urllib import urlencode
|
from urllib import urlencode
|
||||||
|
|
||||||
|
|
||||||
class RESTResponse(io.IOBase):
|
class RESTResponse(io.IOBase):
|
||||||
|
|
||||||
def __init__(self, resp):
|
def __init__(self, resp):
|
||||||
self.urllib3_response = resp
|
self.urllib3_response = resp
|
||||||
self.status = resp.status
|
self.status = resp.status
|
||||||
self.reason = resp.reason
|
self.reason = resp.reason
|
||||||
self.data = resp.data
|
self.data = resp.data
|
||||||
|
|
||||||
def getheaders(self):
|
def getheaders(self):
|
||||||
"""
|
"""
|
||||||
Returns a dictionary of the response headers.
|
Returns a dictionary of the response headers.
|
||||||
"""
|
"""
|
||||||
return self.urllib3_response.getheaders()
|
return self.urllib3_response.getheaders()
|
||||||
|
|
||||||
def getheader(self, name, default=None):
|
def getheader(self, name, default=None):
|
||||||
"""
|
"""
|
||||||
Returns a given response header.
|
Returns a given response header.
|
||||||
"""
|
"""
|
||||||
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):
|
||||||
# http pool manager
|
# http pool manager
|
||||||
self.pool_manager = urllib3.PoolManager(
|
self.pool_manager = urllib3.PoolManager(
|
||||||
num_pools=pools_size
|
num_pools=pools_size
|
||||||
)
|
)
|
||||||
|
|
||||||
# https pool manager
|
# https pool manager
|
||||||
# certificates validated using Mozilla’s root certificates
|
# certificates validated using Mozilla’s root certificates
|
||||||
self.ssl_pool_manager = urllib3.PoolManager(
|
self.ssl_pool_manager = urllib3.PoolManager(
|
||||||
num_pools=pools_size,
|
num_pools=pools_size,
|
||||||
cert_reqs=ssl.CERT_REQUIRED,
|
cert_reqs=ssl.CERT_REQUIRED,
|
||||||
ca_certs=certifi.where()
|
ca_certs=certifi.where()
|
||||||
)
|
)
|
||||||
|
|
||||||
def agent(self, url):
|
def agent(self, url):
|
||||||
"""
|
"""
|
||||||
Return proper pool manager for the http\https schemes.
|
Return proper pool manager for the http\https schemes.
|
||||||
"""
|
"""
|
||||||
url = urllib3.util.url.parse_url(url)
|
url = urllib3.util.url.parse_url(url)
|
||||||
scheme = url.scheme
|
scheme = url.scheme
|
||||||
if scheme == 'https':
|
if scheme == 'https':
|
||||||
return self.ssl_pool_manager
|
return self.ssl_pool_manager
|
||||||
else:
|
else:
|
||||||
return self.pool_manager
|
return self.pool_manager
|
||||||
|
|
||||||
def request(self, method, url, query_params=None, headers=None,
|
def request(self, method, url, query_params=None, headers=None,
|
||||||
body=None, post_params=None):
|
body=None, post_params=None):
|
||||||
"""
|
"""
|
||||||
:param method: http request method
|
:param method: http request method
|
||||||
:param url: http request url
|
:param url: http request url
|
||||||
: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 {}
|
||||||
|
|
||||||
if 'Content-Type' not in headers:
|
if 'Content-Type' not in headers:
|
||||||
headers['Content-Type'] = 'application/json'
|
headers['Content-Type'] = 'application/json'
|
||||||
|
|
||||||
# For `POST`, `PUT`, `PATCH`
|
# For `POST`, `PUT`, `PATCH`
|
||||||
if method in ['POST', 'PUT', 'PATCH']:
|
if method in ['POST', 'PUT', 'PATCH']:
|
||||||
if query_params:
|
if query_params:
|
||||||
url += '?' + urlencode(query_params)
|
url += '?' + urlencode(query_params)
|
||||||
if headers['Content-Type'] == 'application/json':
|
if headers['Content-Type'] == 'application/json':
|
||||||
r = self.agent(url).request(method, url,
|
r = self.agent(url).request(method, url,
|
||||||
body=json.dumps(body),
|
body=json.dumps(body),
|
||||||
headers=headers)
|
headers=headers)
|
||||||
if headers['Content-Type'] == 'application/x-www-form-urlencoded':
|
if headers['Content-Type'] == 'application/x-www-form-urlencoded':
|
||||||
r = self.agent(url).request(method, url,
|
r = self.agent(url).request(method, url,
|
||||||
fields=post_params,
|
fields=post_params,
|
||||||
encode_multipart=False,
|
encode_multipart=False,
|
||||||
headers=headers)
|
headers=headers)
|
||||||
if headers['Content-Type'] == 'multipart/form-data':
|
if headers['Content-Type'] == 'multipart/form-data':
|
||||||
# must del headers['Content-Type'], or the correct Content-Type
|
# must del headers['Content-Type'], or the correct Content-Type
|
||||||
# which generated by urllib3 will be overwritten.
|
# which generated by urllib3 will be overwritten.
|
||||||
del headers['Content-Type']
|
del headers['Content-Type']
|
||||||
r = self.agent(url).request(method, url,
|
r = self.agent(url).request(method, url,
|
||||||
fields=post_params,
|
fields=post_params,
|
||||||
encode_multipart=True,
|
encode_multipart=True,
|
||||||
headers=headers)
|
headers=headers)
|
||||||
# For `GET`, `HEAD`, `DELETE`
|
# For `GET`, `HEAD`, `DELETE`
|
||||||
else:
|
else:
|
||||||
r = self.agent(url).request(method, url,
|
r = self.agent(url).request(method, url,
|
||||||
fields=query_params,
|
fields=query_params,
|
||||||
headers=headers)
|
headers=headers)
|
||||||
r = RESTResponse(r)
|
r = RESTResponse(r)
|
||||||
|
|
||||||
if r.status not in range(200, 206):
|
if r.status not in range(200, 206):
|
||||||
raise ApiException(r)
|
raise ApiException(r)
|
||||||
|
|
||||||
return self.process_response(r)
|
return self.process_response(r)
|
||||||
|
|
||||||
def process_response(self, response):
|
def process_response(self, response):
|
||||||
# In the python 3, the response.data is bytes.
|
# In the python 3, the response.data is bytes.
|
||||||
# we need to decode it to string.
|
# we need to decode it to string.
|
||||||
if sys.version_info > (3,):
|
if sys.version_info > (3,):
|
||||||
data = response.data.decode('utf8')
|
data = response.data.decode('utf8')
|
||||||
else:
|
else:
|
||||||
data = response.data
|
data = response.data
|
||||||
try:
|
try:
|
||||||
resp = json.loads(data)
|
resp = json.loads(data)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
resp = data
|
resp = data
|
||||||
|
|
||||||
return resp
|
return resp
|
||||||
|
|
||||||
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):
|
||||||
"""
|
"""
|
||||||
Non-2xx HTTP response
|
Non-2xx HTTP response
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, http_resp):
|
def __init__(self, http_resp):
|
||||||
self.status = http_resp.status
|
self.status = http_resp.status
|
||||||
self.reason = http_resp.reason
|
self.reason = http_resp.reason
|
||||||
self.body = http_resp.data
|
self.body = http_resp.data
|
||||||
self.headers = http_resp.getheaders()
|
self.headers = http_resp.getheaders()
|
||||||
|
|
||||||
# In the python 3, the self.body is bytes.
|
# In the python 3, the self.body is bytes.
|
||||||
# we need to decode it to string.
|
# we need to decode it to string.
|
||||||
if sys.version_info > (3,):
|
if sys.version_info > (3,):
|
||||||
data = self.body.decode('utf8')
|
data = self.body.decode('utf8')
|
||||||
else:
|
else:
|
||||||
data = self.body
|
data = self.body
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.body = json.loads(data)
|
||||||
|
except ValueError:
|
||||||
|
self.body = data
|
||||||
|
|
||||||
try:
|
def __str__(self):
|
||||||
self.body = json.loads(data)
|
"""
|
||||||
except ValueError:
|
Custom error response messages
|
||||||
self.body = data
|
"""
|
||||||
|
return "({0})\n"\
|
||||||
def __str__(self):
|
"Reason: {1}\n"\
|
||||||
"""
|
"HTTP response headers: {2}\n"\
|
||||||
Custom error response messages
|
"HTTP response body: {3}\n".\
|
||||||
"""
|
format(self.status, self.reason, self.headers, self.body)
|
||||||
return "({0})\n"\
|
|
||||||
"Reason: {1}\n"\
|
|
||||||
"HTTP response headers: {2}\n"\
|
|
||||||
"HTTP response body: {3}\n".\
|
|
||||||
format(self.status, self.reason, self.headers, self.body)
|
|
||||||
|
|
||||||
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.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
IMPL = RESTClientObject()
|
IMPL = RESTClientObject()
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def request(cls, *n, **kw):
|
def request(cls, *n, **kw):
|
||||||
"""
|
"""
|
||||||
Perform a REST request and parse the response.
|
Perform a REST request and parse the response.
|
||||||
"""
|
"""
|
||||||
return cls.IMPL.request(*n, **kw)
|
return cls.IMPL.request(*n, **kw)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def GET(cls, *n, **kw):
|
def GET(cls, *n, **kw):
|
||||||
"""
|
"""
|
||||||
Perform a GET request using `RESTClient.request()`.
|
Perform a GET request using `RESTClient.request()`.
|
||||||
"""
|
"""
|
||||||
return cls.IMPL.GET(*n, **kw)
|
return cls.IMPL.GET(*n, **kw)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def HEAD(cls, *n, **kw):
|
def HEAD(cls, *n, **kw):
|
||||||
"""
|
"""
|
||||||
Perform a HEAD request using `RESTClient.request()`.
|
Perform a HEAD request using `RESTClient.request()`.
|
||||||
"""
|
"""
|
||||||
return cls.IMPL.GET(*n, **kw)
|
return cls.IMPL.GET(*n, **kw)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def POST(cls, *n, **kw):
|
def POST(cls, *n, **kw):
|
||||||
"""
|
"""
|
||||||
Perform a POST request using `RESTClient.request()`
|
Perform a POST request using `RESTClient.request()`
|
||||||
"""
|
"""
|
||||||
return cls.IMPL.POST(*n, **kw)
|
return cls.IMPL.POST(*n, **kw)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def PUT(cls, *n, **kw):
|
def PUT(cls, *n, **kw):
|
||||||
"""
|
"""
|
||||||
Perform a PUT request using `RESTClient.request()`
|
Perform a PUT request using `RESTClient.request()`
|
||||||
"""
|
"""
|
||||||
return cls.IMPL.PUT(*n, **kw)
|
return cls.IMPL.PUT(*n, **kw)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def PATCH(cls, *n, **kw):
|
def PATCH(cls, *n, **kw):
|
||||||
"""
|
"""
|
||||||
Perform a PATCH request using `RESTClient.request()`
|
Perform a PATCH request using `RESTClient.request()`
|
||||||
"""
|
"""
|
||||||
return cls.IMPL.PATCH(*n, **kw)
|
return cls.IMPL.PATCH(*n, **kw)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def DELETE(cls, *n, **kw):
|
def DELETE(cls, *n, **kw):
|
||||||
"""
|
"""
|
||||||
Perform a DELETE request using `RESTClient.request()`
|
Perform a DELETE request using `RESTClient.request()`
|
||||||
"""
|
"""
|
||||||
return cls.IMPL.DELETE(*n, **kw)
|
return cls.IMPL.DELETE(*n, **kw)
|
||||||
|
@ -3,18 +3,18 @@ from setuptools import setup, find_packages
|
|||||||
|
|
||||||
{{#apiInfo}}{{#apis}}{{^hasMore}}
|
{{#apiInfo}}{{#apis}}{{^hasMore}}
|
||||||
|
|
||||||
# To install the library, open a Terminal shell, then run this
|
# To install the library, open a Terminal shell, then run this
|
||||||
# file by typing:
|
# file by typing:
|
||||||
#
|
#
|
||||||
# python setup.py install
|
# python setup.py install
|
||||||
#
|
#
|
||||||
# You need to have the setuptools module installed.
|
# You need to have the setuptools module installed.
|
||||||
# Try reading the setuptools documentation:
|
# Try reading the setuptools documentation:
|
||||||
# http://pypi.python.org/pypi/setuptools
|
# http://pypi.python.org/pypi/setuptools
|
||||||
|
|
||||||
REQUIRES = ["urllib3 >= 1.10", "six >= 1.9", "certifi"]
|
REQUIRES = ["urllib3 >= 1.10", "six >= 1.9", "certifi"]
|
||||||
|
|
||||||
setup(
|
setup(
|
||||||
name="{{module}}",
|
name="{{module}}",
|
||||||
version="{{version}}",
|
version="{{version}}",
|
||||||
description="{{appName}}",
|
description="{{appName}}",
|
||||||
@ -27,7 +27,7 @@ from setuptools import setup, find_packages
|
|||||||
long_description="""\
|
long_description="""\
|
||||||
{{appDescription}}
|
{{appDescription}}
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
|
|
||||||
{{/hasMore}}{{/apis}}{{/apiInfo}}
|
{{/hasMore}}{{/apis}}{{/apiInfo}}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user