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}}
# 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
from six import iteritems
from .. import configuration
from ..configuration import Configuration
from ..api_client import ApiClient
{{#operations}}
class {{classname}}(object):
def __init__(self, api_client=None):
config = Configuration()
if api_client:
self.api_client = api_client
else:
if not configuration.api_client:
configuration.api_client = ApiClient('{{basePath}}')
self.api_client = configuration.api_client
if not config.api_client:
config.api_client = ApiClient('{{basePath}}')
self.api_client = config.api_client
{{#operation}}
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,
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
{{/operation}}
{{/operations}}

View File

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

View File

@ -5,73 +5,117 @@ import httplib
import sys
import logging
def get_api_key_with_prefix(key):
global api_key
global api_key_prefix
def singleton(cls, *args, **kw):
instances = {}
if api_key.get(key) and api_key_prefix.get(key):
return api_key_prefix[key] + ' ' + api_key[key]
elif api_key.get(key):
return api_key[key]
def _singleton():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return _singleton
def setting_logging_enabled():
global logging_file
format = '%(asctime)s %(levelname)s %(message)s'
if logging_file:
logging.basicConfig(filename=logging_file, level=logging.DEBUG, format=format)
else:
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format=format)
httplib.HTTPConnection.debuglevel = 1
def to_debug_report():
return "Python SDK Debug Report:\n"\
"OS: {env}\n"\
"Python Version: {pyversion}\n"\
"Version of the API: {{version}}\n"\
"SDK Package Version: {{packageVersion}}".format(env=sys.platform, pyversion=sys.version)
@singleton
class Configuration(object):
def get_basic_auth_token():
global username
global password
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()
return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization')
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:
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)
def auth_settings():
return { {{#authMethods}}{{#isApiKey}}
'{{name}}': {
'type': 'api_key',
'in': {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}},
'key': '{{keyParamName}}',
'value': get_api_key_with_prefix('{{keyParamName}}')
},
{{/isApiKey}}{{#isBasic}}
'{{name}}': {
'type': 'basic',
'in': 'header',
'key': 'Authorization',
'value': get_basic_auth_token()
},
{{/isBasic}}{{/authMethods}}
}
@property
def logging_file(self):
return self.__logging_file
# Default Base url
host = "{{basePath}}"
@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)
# Default api client
api_client = None
# Authentication settings
@property
def debug(self):
return self.__debug
api_key = {}
api_key_prefix = {}
username = ''
password = ''
@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)
# Temp foloder for file download
temp_folder_path = None
# Logging settings
logging_file = None
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 { {{#authMethods}}{{#isApiKey}}
'{{name}}': {
'type': 'api_key',
'in': {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}},
'key': '{{keyParamName}}',
'value': self.get_api_key_with_prefix('{{keyParamName}}')
},
{{/isApiKey}}{{#isBasic}}
'{{name}}': {
'type': 'basic',
'in': 'header',
'key': 'Authorization',
'value': self.get_basic_auth_token()
},
{{/isBasic}}{{/authMethods}}
}
def to_debug_report(self):
return "Python SDK Debug Report:\n"\
"OS: {env}\n"\
"Python Version: {pyversion}\n"\
"Version of the API: {{version}}\n"\
"SDK Package Version: {{packageVersion}}".format(env=sys.platform, pyversion=sys.version)

View File

@ -130,20 +130,14 @@ class RESTClientObject(object):
headers=headers)
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.
# we need to decode it to string.
if sys.version_info > (3,):
r.data = r.data.decode('utf8')
# log response body
logger.debug("response body: %s" % r.data)
if r.status not in range(200, 206):
raise ApiException(http_resp=r)

View File

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

View File

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

View File

@ -27,18 +27,19 @@ import os
# python 2 and python 3 compatibility library
from six import iteritems
from .. import configuration
from ..configuration import Configuration
from ..api_client import ApiClient
class PetApi(object):
def __init__(self, api_client=None):
config = Configuration()
if api_client:
self.api_client = api_client
else:
if not configuration.api_client:
configuration.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = configuration.api_client
if not config.api_client:
config.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = config.api_client
def update_pet(self, **kwargs):
@ -100,7 +101,7 @@ class PetApi(object):
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
return response
def add_pet(self, **kwargs):
@ -108,9 +109,6 @@ class PetApi(object):
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
to be passed along and invoked when receiving response:
>>> def callback_function(response):
@ -120,7 +118,6 @@ class PetApi(object):
:param callback function: The callback function for asynchronous request. (optional)
:param Pet body: Pet object that needs to be added to the store
>>>>>>> support asynchronous request in python client
:return: None
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
return response
>>>>>>> support asynchronous request in python client
def find_pets_by_status(self, **kwargs):
"""
Finds Pets by status
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
to be passed along and invoked when receiving response:
>>> def callback_function(response):
@ -190,7 +180,6 @@ class PetApi(object):
:param callback function: The callback function for asynchronous request. (optional)
:param list[str] status: Status values that need to be considered for filter
>>>>>>> support asynchronous request in python client
:return: list[Pet]
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
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
response_type='list[Pet]', auth_settings=auth_settings, callback=params.get('callback'))
return response
def find_pets_by_tags(self, **kwargs):
@ -249,9 +233,6 @@ class PetApi(object):
Finds Pets by tags
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
to be passed along and invoked when receiving response:
>>> def callback_function(response):
@ -261,7 +242,6 @@ class PetApi(object):
:param callback function: The callback function for asynchronous request. (optional)
:param list[str] tags: Tags to filter by
>>>>>>> support asynchronous request in python client
:return: list[Pet]
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
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
response_type='list[Pet]', auth_settings=auth_settings, callback=params.get('callback'))
return response
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type='Pet', auth_settings=auth_settings)
=======
response='Pet', auth_settings=auth_settings, callback=params.get('callback'))
>>>>>>> support asynchronous request in python client
response_type='Pet', auth_settings=auth_settings, callback=params.get('callback'))
return response
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 str pet_id: ID of pet that needs to be updated (required)
:param str name: Updated name of the pet (optional)
:param str status: Updated status of the pet (optional)
:param str name: Updated name of the pet
:param str status: Updated status of the pet
:return: None
If the method is called asynchronously, returns the request thread.
@ -457,20 +427,14 @@ class PetApi(object):
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
return response
>>>>>>> support asynchronous request in python client
def delete_pet(self, pet_id, **kwargs):
"""
Deletes a pet
<<<<<<< HEAD
=======
SDK also supports asynchronous requests in which you can define a `callback` function
to be passed along and invoked when receiving response:
>>> def callback_function(response):
@ -479,10 +443,8 @@ class PetApi(object):
>>> thread = api.delete_pet(pet_id, callback=callback_function)
: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 str api_key: (optional)
:param str api_key:
:return: None
If the method is called asynchronously, returns the request thread.
@ -492,12 +454,8 @@ class PetApi(object):
if pet_id is None:
raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`")
<<<<<<< HEAD
all_params = ['pet_id', 'api_key']
=======
all_params = ['api_key', 'pet_id']
all_params.append('callback')
>>>>>>> support asynchronous request in python client
params = locals()
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
return response
>>>>>>> support asynchronous request in python client
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 int pet_id: ID of pet to update (required)
:param str additional_metadata: Additional data to pass to server (optional)
:param file file: file to upload (optional)
:param str additional_metadata: Additional data to pass to server
:param file file: file to upload
:return: None
If the method is called asynchronously, returns the request thread.
@ -617,19 +571,6 @@ class PetApi(object):
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
return response
>>>>>>> support asynchronous request in python client

View File

@ -27,18 +27,19 @@ import os
# python 2 and python 3 compatibility library
from six import iteritems
from .. import configuration
from ..configuration import Configuration
from ..api_client import ApiClient
class StoreApi(object):
def __init__(self, api_client=None):
config = Configuration()
if api_client:
self.api_client = api_client
else:
if not configuration.api_client:
configuration.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = configuration.api_client
if not config.api_client:
config.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = config.api_client
def get_inventory(self, **kwargs):
@ -96,12 +97,7 @@ class StoreApi(object):
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
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
response_type='dict(str, int)', auth_settings=auth_settings, callback=params.get('callback'))
return response
def place_order(self, **kwargs):
@ -109,9 +105,6 @@ class StoreApi(object):
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
to be passed along and invoked when receiving response:
>>> def callback_function(response):
@ -121,7 +114,6 @@ class StoreApi(object):
:param callback function: The callback function for asynchronous request. (optional)
:param Order body: order placed for purchasing the pet
>>>>>>> support asynchronous request in python client
:return: Order
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type='Order', auth_settings=auth_settings)
=======
response='Order', auth_settings=auth_settings, callback=params.get('callback'))
>>>>>>> support asynchronous request in python client
response_type='Order', auth_settings=auth_settings, callback=params.get('callback'))
return response
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type='Order', auth_settings=auth_settings)
=======
response='Order', auth_settings=auth_settings, callback=params.get('callback'))
>>>>>>> support asynchronous request in python client
response_type='Order', auth_settings=auth_settings, callback=params.get('callback'))
return response
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
return response
>>>>>>> support asynchronous request in python client

View File

@ -27,18 +27,19 @@ import os
# python 2 and python 3 compatibility library
from six import iteritems
from .. import configuration
from ..configuration import Configuration
from ..api_client import ApiClient
class UserApi(object):
def __init__(self, api_client=None):
config = Configuration()
if api_client:
self.api_client = api_client
else:
if not configuration.api_client:
configuration.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = configuration.api_client
if not config.api_client:
config.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = config.api_client
def create_user(self, **kwargs):
@ -46,9 +47,6 @@ class UserApi(object):
Create 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
to be passed along and invoked when receiving response:
>>> def callback_function(response):
@ -58,7 +56,6 @@ class UserApi(object):
:param callback function: The callback function for asynchronous request. (optional)
:param User body: Created user object
>>>>>>> support asynchronous request in python client
:return: None
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
return response
>>>>>>> support asynchronous request in python client
def create_users_with_array_input(self, **kwargs):
"""
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
to be passed along and invoked when receiving response:
>>> def callback_function(response):
@ -128,7 +118,6 @@ class UserApi(object):
:param callback function: The callback function for asynchronous request. (optional)
:param list[User] body: List of user object
>>>>>>> support asynchronous request in python client
:return: None
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
return response
>>>>>>> support asynchronous request in python client
def create_users_with_list_input(self, **kwargs):
"""
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
to be passed along and invoked when receiving response:
>>> def callback_function(response):
@ -198,7 +180,6 @@ class UserApi(object):
:param callback function: The callback function for asynchronous request. (optional)
:param list[User] body: List of user object
>>>>>>> support asynchronous request in python client
:return: None
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
return response
>>>>>>> support asynchronous request in python client
def login_user(self, **kwargs):
"""
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
to be passed along and invoked when receiving response:
>>> def callback_function(response):
@ -270,7 +243,6 @@ class UserApi(object):
:param callback function: The callback function for asynchronous request. (optional)
:param str username: The user name for login
:param str password: The password for login in clear text
>>>>>>> support asynchronous request in python client
:return: str
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type='str', auth_settings=auth_settings)
=======
response='str', auth_settings=auth_settings, callback=params.get('callback'))
>>>>>>> support asynchronous request in python client
response_type='str', auth_settings=auth_settings, callback=params.get('callback'))
return response
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
return response
>>>>>>> support asynchronous request in python client
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type='User', auth_settings=auth_settings)
=======
response='User', auth_settings=auth_settings, callback=params.get('callback'))
>>>>>>> support asynchronous request in python client
response_type='User', auth_settings=auth_settings, callback=params.get('callback'))
return response
def update_user(self, username, **kwargs):
@ -474,7 +432,7 @@ class UserApi(object):
:param callback function: The callback function for asynchronous request. (optional)
:param str username: name that need to be deleted (required)
:param User body: Updated user object (optional)
:param User body: Updated user object
:return: None
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
return response
>>>>>>> support asynchronous request in python client
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,
body=body_params, post_params=form_params, files=files,
<<<<<<< HEAD
response_type=None, auth_settings=auth_settings)
=======
response=None, auth_settings=auth_settings, callback=params.get('callback'))
response_type=None, auth_settings=auth_settings, callback=params.get('callback'))
return response
>>>>>>> support asynchronous request in python client

View File

@ -5,65 +5,110 @@ import httplib
import sys
import logging
def get_api_key_with_prefix(key):
global api_key
global api_key_prefix
def singleton(cls, *args, **kw):
instances = {}
if api_key.get(key) and api_key_prefix.get(key):
return api_key_prefix[key] + ' ' + api_key[key]
elif api_key.get(key):
return api_key[key]
def _singleton():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return _singleton
def setting_logging_enabled():
global logging_file
format = '%(asctime)s %(levelname)s %(message)s'
if logging_file:
logging.basicConfig(filename=logging_file, level=logging.DEBUG, format=format)
else:
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG, format=format)
httplib.HTTPConnection.debuglevel = 1
def to_debug_report():
return "Python SDK Debug Report:\n"\
"OS: {env}\n"\
"Python Version: {pyversion}\n"\
"Version of the API: 1.0.0\n"\
"SDK Package Version: 1.0.0".format(env=sys.platform, pyversion=sys.version)
@singleton
class Configuration(object):
def get_basic_auth_token():
global username
global password
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()
return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization')
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:
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)
def auth_settings():
return {
'api_key': {
'type': 'api_key',
'in': 'header',
'key': 'api_key',
'value': get_api_key_with_prefix('api_key')
},
}
@property
def logging_file(self):
return self.__logging_file
# Default Base url
host = "http://petstore.swagger.io/v2"
@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"\
"OS: {env}\n"\
"Python Version: {pyversion}\n"\
"Version of the API: 1.0.0\n"\
"SDK Package Version: 1.0.0".format(env=sys.platform, pyversion=sys.version)
# 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)
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.
# we need to decode it to string.
if sys.version_info > (3,):
r.data = r.data.decode('utf8')
# log response body
logger.debug("response body: %s" % r.data)
if r.status not in range(200, 206):
raise ApiException(http_resp=r)