Update logging of python client

This commit is contained in:
geekerzp 2015-07-11 11:52:12 +08:00
parent 517717958d
commit 4d302683f3
12 changed files with 279 additions and 350 deletions

View File

@ -8,3 +8,7 @@ from __future__ import absolute_import
{{/apis}}{{/apiInfo}} {{/apis}}{{/apiInfo}}
# import ApiClient # import ApiClient
from .api_client import ApiClient from .api_client import ApiClient
from .configuration import Configuration
configuration = Configuration()

View File

@ -27,19 +27,20 @@ import os
# python 2 and python 3 compatibility library # python 2 and python 3 compatibility library
from six import iteritems from six import iteritems
from .. import configuration from ..configuration 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):
config = Configuration()
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 config.api_client:
configuration.api_client = ApiClient('{{basePath}}') config.api_client = ApiClient('{{basePath}}')
self.api_client = configuration.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):
@ -117,16 +118,7 @@ class {{classname}}(object):
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, callback=params.get('callback')) 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

@ -31,7 +31,7 @@ except ImportError:
# for python2 # for python2
from urllib import quote from urllib import quote
from . import configuration from .configuration import Configuration
class ApiClient(object): class ApiClient(object):
""" """
@ -41,7 +41,7 @@ class ApiClient(object):
: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
@ -62,7 +62,7 @@ class ApiClient(object):
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, callback=None): body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None):
# headers parameters # headers parameters
header_params = header_params or {} header_params = header_params or {}
@ -221,7 +221,7 @@ class ApiClient(object):
def call_api(self, resource_path, method, def call_api(self, resource_path, method,
path_params=None, query_params=None, header_params=None, path_params=None, query_params=None, header_params=None,
body=None, post_params=None, files=None, body=None, post_params=None, files=None,
response=None, auth_settings=None, callback=None): response_type=None, auth_settings=None, callback=None):
""" """
Perform http request and return deserialized data Perform http request and return deserialized data
@ -247,13 +247,13 @@ class ApiClient(object):
return self.__call_api(resource_path, method, return self.__call_api(resource_path, method,
path_params, query_params, header_params, path_params, query_params, header_params,
body, post_params, files, body, post_params, files,
response, auth_settings, callback) response_type, auth_settings, callback)
else: else:
thread = threading.Thread(target=self.__call_api, thread = threading.Thread(target=self.__call_api,
args=(resource_path, method, args=(resource_path, method,
path_params, query_params, header_params, path_params, query_params, header_params,
body, post_params, files, body, post_params, files,
response, auth_settings, callback)) response_type, auth_settings, callback))
thread.start() thread.start()
return thread return thread
@ -326,11 +326,13 @@ class ApiClient(object):
""" """
Update header and query params based on authentication setting Update header and query params based on authentication setting
""" """
config = Configuration()
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 = config.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']

View File

@ -5,73 +5,117 @@ import httplib
import sys import sys
import logging import logging
def get_api_key_with_prefix(key): def singleton(cls, *args, **kw):
global api_key instances = {}
global api_key_prefix
if api_key.get(key) and api_key_prefix.get(key): def _singleton():
return api_key_prefix[key] + ' ' + api_key[key] if cls not in instances:
elif api_key.get(key): instances[cls] = cls(*args, **kw)
return api_key[key] return instances[cls]
return _singleton
def setting_logging_enabled():
global logging_file @singleton
format = '%(asctime)s %(levelname)s %(message)s' class Configuration(object):
if logging_file:
logging.basicConfig(filename=logging_file, level=logging.DEBUG, format=format) def __init__(self):
# Default Base url
self.host = "{{basePath}}"
# Default api client
self.api_client = None
# Authentication Settings
self.api_key = {}
self.api_key_prefix = {}
self.username = ""
self.password = ""
# Logging Settings
self.logging_format = '%(asctime)s %(levelname)s %(message)s'
self.__logging_file = None
self.__debug = False
self.init_logger()
def init_logger(self):
self.logger = logging.getLogger()
formatter = logging.Formatter(self.logging_format)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
self.logger.addHandler(stream_handler)
if self.__debug:
self.logger.setLevel(logging.DEBUG)
else: else:
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format=format) self.logger.setLevel(logging.WARNING)
if self.__logging_file:
file_handler = logging.FileHandler(self.__logging_file)
file_handler.setFormatter(formatter)
self.logger.addFilter(file_handler)
@property
def logging_file(self):
return self.__logging_file
@logging_file.setter
def logging_file(self, value):
self.__logging_file = value
if self.__logging_file:
formater = logging.Formatter(self.logging_format)
file_handler = logging.FileHandler(self.__logging_file)
file_handler.setFormatter(formater)
self.logger.addHandler(file_handler)
@property
def debug(self):
return self.__debug
@debug.setter
def debug(self, value):
self.__debug = value
if self.__debug:
# if debug status is True, turn on debug logging
self.logger.setLevel(logging.DEBUG)
# turn on httplib debug
httplib.HTTPConnection.debuglevel = 1 httplib.HTTPConnection.debuglevel = 1
else:
# if debug status is False, turn off debug logging,
# setting log level to default `logging.WARNING`
self.logger.setLevel(logging.WARNING)
def to_debug_report(): def get_api_key_with_prefix(self, key):
return "Python SDK Debug Report:\n"\ """ Return api key prepend prefix for key """
"OS: {env}\n"\ if self.api_key.get(key) and self.api_key_prefix.get(key):
"Python Version: {pyversion}\n"\ return self.api_key_prefix[key] + ' ' + self.api_key[key]
"Version of the API: {{version}}\n"\ elif self.api_key.get(key):
"SDK Package Version: {{packageVersion}}".format(env=sys.platform, pyversion=sys.version) return self.api_key[key]
def get_basic_auth_token(): def get_basic_auth_token(self):
global username """ Return basic auth header string """
global password return urllib3.util.make_headers(basic_auth=self.username + ':' + self.password)\
.get('authorization')
return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization') def auth_settings(self):
""" Return Auth Settings for api client """
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': self.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': self.get_basic_auth_token()
}, },
{{/isBasic}}{{/authMethods}} {{/isBasic}}{{/authMethods}}
} }
# Default Base url def to_debug_report(self):
host = "{{basePath}}" return "Python SDK Debug Report:\n"\
"OS: {env}\n"\
# Default api client "Python Version: {pyversion}\n"\
api_client = None "Version of the API: {{version}}\n"\
"SDK Package Version: {{packageVersion}}".format(env=sys.platform, pyversion=sys.version)
# Authentication settings
api_key = {}
api_key_prefix = {}
username = ''
password = ''
# Temp foloder for file download
temp_folder_path = None
# Logging settings
logging_file = None

View File

@ -130,20 +130,14 @@ class RESTClientObject(object):
headers=headers) headers=headers)
r = RESTResponse(r) r = RESTResponse(r)
# log response body
logger.debug("response body: %s" % r.data)
if r.status not in range(200, 206):
raise ApiException(r)
return self.process_response(r)
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,):
r.data = r.data.decode('utf8') r.data = r.data.decode('utf8')
# log response body
logger.debug("response body: %s" % r.data)
if r.status not in range(200, 206): if r.status not in range(200, 206):
raise ApiException(http_resp=r) raise ApiException(http_resp=r)

View File

@ -14,3 +14,7 @@ from .apis.store_api import StoreApi
# import ApiClient # import ApiClient
from .api_client import ApiClient from .api_client import ApiClient
from .configuration import Configuration
configuration = Configuration()

View File

@ -31,7 +31,7 @@ except ImportError:
# for python2 # for python2
from urllib import quote from urllib import quote
from . import configuration from .configuration import Configuration
class ApiClient(object): class ApiClient(object):
""" """
@ -41,7 +41,7 @@ class ApiClient(object):
: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
@ -62,7 +62,7 @@ class ApiClient(object):
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, callback=None): body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None):
# headers parameters # headers parameters
header_params = header_params or {} header_params = header_params or {}
@ -106,8 +106,8 @@ class ApiClient(object):
self.last_response = response_data self.last_response = response_data
# deserialize response data # deserialize response data
if response: if response_type:
deserialized_data = self.deserialize(response_data, response) deserialized_data = self.deserialize(response_data, response_type)
else: else:
deserialized_data = None deserialized_data = None
@ -221,7 +221,7 @@ class ApiClient(object):
def call_api(self, resource_path, method, def call_api(self, resource_path, method,
path_params=None, query_params=None, header_params=None, path_params=None, query_params=None, header_params=None,
body=None, post_params=None, files=None, body=None, post_params=None, files=None,
response=None, auth_settings=None, callback=None): response_type=None, auth_settings=None, callback=None):
""" """
Perform http request and return deserialized data Perform http request and return deserialized data
@ -247,13 +247,13 @@ class ApiClient(object):
return self.__call_api(resource_path, method, return self.__call_api(resource_path, method,
path_params, query_params, header_params, path_params, query_params, header_params,
body, post_params, files, body, post_params, files,
response, auth_settings, callback) response_type, auth_settings, callback)
else: else:
thread = threading.Thread(target=self.__call_api, thread = threading.Thread(target=self.__call_api,
args=(resource_path, method, args=(resource_path, method,
path_params, query_params, header_params, path_params, query_params, header_params,
body, post_params, files, body, post_params, files,
response, auth_settings, callback)) response_type, auth_settings, callback))
thread.start() thread.start()
return thread return thread
@ -326,11 +326,13 @@ class ApiClient(object):
""" """
Update header and query params based on authentication setting Update header and query params based on authentication setting
""" """
config = Configuration()
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 = config.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']

View File

@ -27,18 +27,19 @@ import os
# python 2 and python 3 compatibility library # python 2 and python 3 compatibility library
from six import iteritems from six import iteritems
from .. 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):
config = Configuration()
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 config.api_client:
configuration.api_client = ApiClient('http://petstore.swagger.io/v2') config.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = configuration.api_client self.api_client = config.api_client
def update_pet(self, **kwargs): def update_pet(self, **kwargs):
@ -100,7 +101,7 @@ class PetApi(object):
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=None, auth_settings=auth_settings, callback=params.get('callback')) 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):
@ -108,9 +109,6 @@ class PetApi(object):
Add a new pet to the store Add a new pet to the store
<<<<<<< HEAD
:param Pet body: Pet object that needs to be added to the store (optional)
=======
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):
@ -120,7 +118,6 @@ class PetApi(object):
: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
>>>>>>> support asynchronous request in python client
:return: None :return: None
If the method is called asynchronously, returns the request thread. If the method is called asynchronously, returns the request thread.
@ -166,21 +163,14 @@ class PetApi(object):
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,
<<<<<<< HEAD response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
return response return response
>>>>>>> support asynchronous request in python client
def find_pets_by_status(self, **kwargs): def find_pets_by_status(self, **kwargs):
""" """
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
<<<<<<< HEAD
:param list[str] status: Status values that need to be considered for filter (optional)
=======
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):
@ -190,7 +180,6 @@ class PetApi(object):
: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
>>>>>>> support asynchronous request in python client
: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.
@ -236,12 +225,7 @@ class PetApi(object):
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,
<<<<<<< HEAD response_type='list[Pet]', auth_settings=auth_settings, callback=params.get('callback'))
response_type='list[Pet]', auth_settings=auth_settings)
=======
response='list[Pet]', auth_settings=auth_settings, callback=params.get('callback'))
>>>>>>> support asynchronous request in python client
return response return response
def find_pets_by_tags(self, **kwargs): def find_pets_by_tags(self, **kwargs):
@ -249,9 +233,6 @@ 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.
<<<<<<< HEAD
:param list[str] tags: Tags to filter by (optional)
=======
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):
@ -261,7 +242,6 @@ class PetApi(object):
: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
>>>>>>> support asynchronous request in python client
: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.
@ -307,12 +287,7 @@ class PetApi(object):
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,
<<<<<<< HEAD response_type='list[Pet]', auth_settings=auth_settings, callback=params.get('callback'))
response_type='list[Pet]', auth_settings=auth_settings)
=======
response='list[Pet]', auth_settings=auth_settings, callback=params.get('callback'))
>>>>>>> support asynchronous request in python client
return response return response
def get_pet_by_id(self, pet_id, **kwargs): def get_pet_by_id(self, pet_id, **kwargs):
@ -378,12 +353,7 @@ class PetApi(object):
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,
<<<<<<< HEAD response_type='Pet', auth_settings=auth_settings, callback=params.get('callback'))
response_type='Pet', auth_settings=auth_settings)
=======
response='Pet', auth_settings=auth_settings, callback=params.get('callback'))
>>>>>>> support asynchronous request in python client
return response return response
def update_pet_with_form(self, pet_id, **kwargs): def update_pet_with_form(self, pet_id, **kwargs):
@ -400,8 +370,8 @@ class PetApi(object):
: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 (optional) :param str name: Updated name of the pet
:param str status: Updated status of the pet (optional) :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.
@ -457,20 +427,14 @@ class PetApi(object):
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,
<<<<<<< HEAD response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
return response return response
>>>>>>> support asynchronous request in python client
def delete_pet(self, pet_id, **kwargs): def delete_pet(self, pet_id, **kwargs):
""" """
Deletes a pet Deletes a pet
<<<<<<< HEAD
=======
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):
@ -479,10 +443,8 @@ class PetApi(object):
>>> 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 str api_key:
>>>>>>> support asynchronous request in python client
:param int pet_id: Pet id to delete (required) :param int pet_id: Pet id to delete (required)
:param str api_key: (optional) :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.
@ -492,12 +454,8 @@ class PetApi(object):
if pet_id is None: if pet_id is None:
raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`")
<<<<<<< HEAD
all_params = ['pet_id', 'api_key'] all_params = ['pet_id', 'api_key']
=======
all_params = ['api_key', 'pet_id']
all_params.append('callback') all_params.append('callback')
>>>>>>> support asynchronous request in python client
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
@ -539,12 +497,8 @@ class PetApi(object):
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,
<<<<<<< HEAD response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
return response return response
>>>>>>> support asynchronous request in python client
def upload_file(self, pet_id, **kwargs): def upload_file(self, pet_id, **kwargs):
""" """
@ -560,8 +514,8 @@ class PetApi(object):
: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 (optional) :param str additional_metadata: Additional data to pass to server
:param file file: file to upload (optional) :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.
@ -617,19 +571,6 @@ class PetApi(object):
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,
<<<<<<< HEAD response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
return response return response
>>>>>>> support asynchronous request in python client

View File

@ -27,18 +27,19 @@ import os
# python 2 and python 3 compatibility library # python 2 and python 3 compatibility library
from six import iteritems from six import iteritems
from .. 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):
config = Configuration()
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 config.api_client:
configuration.api_client = ApiClient('http://petstore.swagger.io/v2') config.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = configuration.api_client self.api_client = config.api_client
def get_inventory(self, **kwargs): def get_inventory(self, **kwargs):
@ -96,12 +97,7 @@ class StoreApi(object):
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,
<<<<<<< HEAD response_type='dict(str, int)', auth_settings=auth_settings, callback=params.get('callback'))
response_type='dict(str, int)', auth_settings=auth_settings)
=======
response='dict(str, int)', auth_settings=auth_settings, callback=params.get('callback'))
>>>>>>> support asynchronous request in python client
return response return response
def place_order(self, **kwargs): def place_order(self, **kwargs):
@ -109,9 +105,6 @@ class StoreApi(object):
Place an order for a pet Place an order for a pet
<<<<<<< HEAD
:param Order body: order placed for purchasing the pet (optional)
=======
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):
@ -121,7 +114,6 @@ class StoreApi(object):
: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
>>>>>>> support asynchronous request in python client
:return: Order :return: Order
If the method is called asynchronously, returns the request thread. If the method is called asynchronously, returns the request thread.
@ -167,12 +159,7 @@ class StoreApi(object):
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,
<<<<<<< HEAD response_type='Order', auth_settings=auth_settings, callback=params.get('callback'))
response_type='Order', auth_settings=auth_settings)
=======
response='Order', auth_settings=auth_settings, callback=params.get('callback'))
>>>>>>> support asynchronous request in python client
return response return response
def get_order_by_id(self, order_id, **kwargs): def get_order_by_id(self, order_id, **kwargs):
@ -238,12 +225,7 @@ class StoreApi(object):
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,
<<<<<<< HEAD response_type='Order', auth_settings=auth_settings, callback=params.get('callback'))
response_type='Order', auth_settings=auth_settings)
=======
response='Order', auth_settings=auth_settings, callback=params.get('callback'))
>>>>>>> support asynchronous request in python client
return response return response
def delete_order(self, order_id, **kwargs): def delete_order(self, order_id, **kwargs):
@ -309,19 +291,6 @@ class StoreApi(object):
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,
<<<<<<< HEAD response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
return response return response
>>>>>>> support asynchronous request in python client

View File

@ -27,18 +27,19 @@ import os
# python 2 and python 3 compatibility library # python 2 and python 3 compatibility library
from six import iteritems from six import iteritems
from .. 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):
config = Configuration()
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 config.api_client:
configuration.api_client = ApiClient('http://petstore.swagger.io/v2') config.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = configuration.api_client self.api_client = config.api_client
def create_user(self, **kwargs): def create_user(self, **kwargs):
@ -46,9 +47,6 @@ class UserApi(object):
Create user Create user
This can only be done by the logged in user. This can only be done by the logged in user.
<<<<<<< HEAD
:param User body: Created user object (optional)
=======
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):
@ -58,7 +56,6 @@ class UserApi(object):
: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
>>>>>>> support asynchronous request in python client
:return: None :return: None
If the method is called asynchronously, returns the request thread. If the method is called asynchronously, returns the request thread.
@ -104,21 +101,14 @@ class UserApi(object):
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,
<<<<<<< HEAD response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
return response return response
>>>>>>> support asynchronous request in python client
def create_users_with_array_input(self, **kwargs): def create_users_with_array_input(self, **kwargs):
""" """
Creates list of users with given input array Creates list of users with given input array
<<<<<<< HEAD
:param list[User] body: List of user object (optional)
=======
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):
@ -128,7 +118,6 @@ class UserApi(object):
: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
>>>>>>> support asynchronous request in python client
:return: None :return: None
If the method is called asynchronously, returns the request thread. If the method is called asynchronously, returns the request thread.
@ -174,21 +163,14 @@ class UserApi(object):
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,
<<<<<<< HEAD response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
return response return response
>>>>>>> support asynchronous request in python client
def create_users_with_list_input(self, **kwargs): def create_users_with_list_input(self, **kwargs):
""" """
Creates list of users with given input array Creates list of users with given input array
<<<<<<< HEAD
:param list[User] body: List of user object (optional)
=======
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):
@ -198,7 +180,6 @@ class UserApi(object):
: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
>>>>>>> support asynchronous request in python client
:return: None :return: None
If the method is called asynchronously, returns the request thread. If the method is called asynchronously, returns the request thread.
@ -244,22 +225,14 @@ class UserApi(object):
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,
<<<<<<< HEAD response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
return response return response
>>>>>>> support asynchronous request in python client
def login_user(self, **kwargs): def login_user(self, **kwargs):
""" """
Logs user into the system Logs user into the system
<<<<<<< HEAD
:param str username: The user name for login (optional)
:param str password: The password for login in clear text (optional)
=======
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):
@ -270,7 +243,6 @@ class UserApi(object):
: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
>>>>>>> support asynchronous request in python client
:return: str :return: str
If the method is called asynchronously, returns the request thread. If the method is called asynchronously, returns the request thread.
@ -319,12 +291,7 @@ class UserApi(object):
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,
<<<<<<< HEAD response_type='str', auth_settings=auth_settings, callback=params.get('callback'))
response_type='str', auth_settings=auth_settings)
=======
response='str', auth_settings=auth_settings, callback=params.get('callback'))
>>>>>>> support asynchronous request in python client
return response return response
def logout_user(self, **kwargs): def logout_user(self, **kwargs):
@ -382,12 +349,8 @@ class UserApi(object):
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,
<<<<<<< HEAD response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
return response return response
>>>>>>> support asynchronous request in python client
def get_user_by_name(self, username, **kwargs): def get_user_by_name(self, username, **kwargs):
""" """
@ -452,12 +415,7 @@ class UserApi(object):
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,
<<<<<<< HEAD response_type='User', auth_settings=auth_settings, callback=params.get('callback'))
response_type='User', auth_settings=auth_settings)
=======
response='User', auth_settings=auth_settings, callback=params.get('callback'))
>>>>>>> support asynchronous request in python client
return response return response
def update_user(self, username, **kwargs): def update_user(self, username, **kwargs):
@ -474,7 +432,7 @@ class UserApi(object):
: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 (optional) :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.
@ -527,12 +485,8 @@ class UserApi(object):
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,
<<<<<<< HEAD response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
return response return response
>>>>>>> support asynchronous request in python client
def delete_user(self, username, **kwargs): def delete_user(self, username, **kwargs):
""" """
@ -597,19 +551,6 @@ class UserApi(object):
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,
<<<<<<< HEAD response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
return response return response
>>>>>>> support asynchronous request in python client

View File

@ -5,65 +5,110 @@ import httplib
import sys import sys
import logging import logging
def get_api_key_with_prefix(key): def singleton(cls, *args, **kw):
global api_key instances = {}
global api_key_prefix
if api_key.get(key) and api_key_prefix.get(key): def _singleton():
return api_key_prefix[key] + ' ' + api_key[key] if cls not in instances:
elif api_key.get(key): instances[cls] = cls(*args, **kw)
return api_key[key] return instances[cls]
return _singleton
def setting_logging_enabled():
global logging_file @singleton
format = '%(asctime)s %(levelname)s %(message)s' class Configuration(object):
if logging_file:
logging.basicConfig(filename=logging_file, level=logging.DEBUG, format=format) def __init__(self):
# Default Base url
self.host = "http://petstore.swagger.io/v2"
# Default api client
self.api_client = None
# Authentication Settings
self.api_key = {}
self.api_key_prefix = {}
self.username = ""
self.password = ""
# Logging Settings
self.logging_format = '%(asctime)s %(levelname)s %(message)s'
self.__logging_file = None
self.__debug = False
self.init_logger()
def init_logger(self):
self.logger = logging.getLogger()
formatter = logging.Formatter(self.logging_format)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
self.logger.addHandler(stream_handler)
if self.__debug:
self.logger.setLevel(logging.DEBUG)
else: else:
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format=format) self.logger.setLevel(logging.WARNING)
httplib.HTTPConnection.debuglevel = 1 if self.__logging_file:
file_handler = logging.FileHandler(self.__logging_file)
file_handler.setFormatter(formatter)
self.logger.addFilter(file_handler)
def to_debug_report(): @property
def logging_file(self):
return self.__logging_file
@logging_file.setter
def logging_file(self, value):
self.__logging_file = value
if self.__logging_file:
formater = logging.Formatter(self.logging_format)
file_handler = logging.FileHandler(self.__logging_file)
file_handler.setFormatter(formater)
self.logger.addHandler(file_handler)
@property
def debug(self):
return self.__debug
@debug.setter
def debug(self, value):
self.__debug = value
if self.__debug:
# if debug status is True, turn on debug logging
self.logger.setLevel(logging.DEBUG)
# turn on httplib debug
httplib.HTTPConnection.debuglevel = 1
else:
# if debug status is False, turn off debug logging,
# setting log level to default `logging.WARNING`
self.logger.setLevel(logging.WARNING)
def get_api_key_with_prefix(self, key):
""" Return api key prepend prefix for key """
if self.api_key.get(key) and self.api_key_prefix.get(key):
return self.api_key_prefix[key] + ' ' + self.api_key[key]
elif self.api_key.get(key):
return self.api_key[key]
def get_basic_auth_token(self):
""" Return basic auth header string """
return urllib3.util.make_headers(basic_auth=self.username + ':' + self.password)\
.get('authorization')
def auth_settings(self):
""" Return Auth Settings for api client """
return {
'api_key': {
'type': 'api_key',
'in': 'header',
'key': 'api_key',
'value': self.get_api_key_with_prefix('api_key')
},
}
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)
def get_basic_auth_token():
global username
global password
return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization')
def auth_settings():
return {
'api_key': {
'type': 'api_key',
'in': 'header',
'key': 'api_key',
'value': get_api_key_with_prefix('api_key')
},
}
# Default Base url
host = "http://petstore.swagger.io/v2"
# Default api client
api_client = None
# Authentication settings
api_key = {}
api_key_prefix = {}
username = ''
password = ''
<<<<<<< HEAD
# Temp foloder for file download
temp_folder_path = None
=======
# Logging settings
logging_file = None
>>>>>>> Add logging and debug report for python client.

View File

@ -130,23 +130,14 @@ class RESTClientObject(object):
headers=headers) headers=headers)
r = RESTResponse(r) r = RESTResponse(r)
<<<<<<< HEAD
=======
# log response body
logger.debug("response body: %s" % r.data)
if r.status not in range(200, 206):
raise ApiException(r)
return self.process_response(r)
def process_response(self, response):
>>>>>>> Add logging and debug report for python client.
# 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,):
r.data = r.data.decode('utf8') r.data = r.data.decode('utf8')
# log response body
logger.debug("response body: %s" % r.data)
if r.status not in range(200, 206): if r.status not in range(200, 206):
raise ApiException(http_resp=r) raise ApiException(http_resp=r)