Various python cleanups (#3650)

* python: Let logging format messages on demand

* python: Use six more

* python: Remove unused imports

* python: flake8 fixes

* python: Make examples compatible with Python 3

* python: Spelling fixes
This commit is contained in:
Ville Skyttä 2016-08-30 05:16:17 +03:00 committed by wing328
parent d8406c0dd0
commit 224fd208e7
14 changed files with 94 additions and 126 deletions

View File

@ -51,6 +51,7 @@ import {{{packageName}}}
Please follow the [installation procedure](#installation--usage) and then run the following:
```python
from __future__ import print_function
import time
import {{{packageName}}}
from {{{packageName}}}.rest import ApiException
@ -76,7 +77,7 @@ try:
{{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}}
pprint(api_response){{/returnType}}
except ApiException as e:
print "Exception when calling {{classname}}->{{operationId}}: %s\n" % e
print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e)
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
```

View File

@ -19,17 +19,15 @@ Copyright 2016 SmartBear Software
"""
from __future__ import absolute_import
from . import models
from .rest import RESTClientObject
from .rest import ApiException
import os
import re
import sys
import urllib
import json
import mimetypes
import random
import tempfile
import threading
@ -37,22 +35,8 @@ from datetime import datetime
from datetime import date
# python 2 and python 3 compatibility library
from six import iteritems
try:
# for python3
from urllib.parse import quote
except ImportError:
# for python2
from urllib import quote
# special handling of `long` (python2 only)
try:
# Python 2
long
except NameError:
# Python 3
long = int
from six import PY3, integer_types, iteritems, text_type
from six.moves.urllib.parse import quote
from .configuration import Configuration
@ -113,7 +97,7 @@ class ApiClient(object):
body=None, post_params=None, files=None,
response_type=None, auth_settings=None, callback=None, _return_http_data_only=None):
# headers parameters
# header parameters
header_params = header_params or {}
header_params.update(self.default_headers)
if self.cookie:
@ -167,11 +151,10 @@ class ApiClient(object):
if callback:
callback(deserialized_data) if _return_http_data_only else callback((deserialized_data, response_data.status, response_data.getheaders()))
elif _return_http_data_only:
return ( deserialized_data );
return (deserialized_data)
else:
return (deserialized_data, response_data.status, response_data.getheaders())
def to_path_value(self, obj):
"""
Takes value and turn it into a string suitable for inclusion in
@ -201,9 +184,7 @@ class ApiClient(object):
:param obj: The data to serialize.
:return: The serialized form of data.
"""
types = (str, int, long, float, bool, tuple)
if sys.version_info < (3, 0):
types = types + (unicode,)
types = (str, float, bool, tuple) + tuple(integer_types) + (text_type,)
if isinstance(obj, type(None)):
return None
elif isinstance(obj, types):
@ -235,7 +216,7 @@ class ApiClient(object):
:param response: RESTResponse object to be deserialized.
:param response_type: class literal for
deserialzied object, or string of class name.
deserialized object, or string of class name.
:return: deserialized object.
"""
@ -277,14 +258,16 @@ class ApiClient(object):
# convert str to class
# for native types
if klass in ['int', 'long', 'float', 'str', 'bool',
if klass in ['int', 'float', 'str', 'bool',
"date", 'datetime', "object"]:
klass = eval(klass)
elif klass == 'long':
klass = int if PY3 else long
# for model types
else:
klass = eval('models.' + klass)
if klass in [int, long, float, str, bool]:
if klass in integer_types or klass in (float, str, bool):
return self.__deserialize_primitive(data, klass)
elif klass == object:
return self.__deserialize_object(data)
@ -339,7 +322,7 @@ class ApiClient(object):
header_params, body,
post_params, files,
response_type, auth_settings,
callback,_return_http_data_only))
callback, _return_http_data_only))
thread.start()
return thread

View File

@ -19,6 +19,7 @@ Method | HTTP request | Description
### Example
```python
from __future__ import print_statement
import time
import {{{packageName}}}
from {{{packageName}}}.rest import ApiException
@ -45,7 +46,7 @@ try:
{{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}}
pprint(api_response){{/returnType}}
except ApiException as e:
print "Exception when calling {{classname}}->{{operationId}}: %s\n" % e
print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e)
```
### Parameters

View File

@ -3,19 +3,14 @@
{{>partial_header}}
from __future__ import absolute_import
import base64
import urllib3
try:
import httplib
except ImportError:
# for python3
import http.client as httplib
import urllib3
import sys
import logging
from six import iteritems
from six.moves import http_client as httplib
def singleton(cls, *args, **kw):
@ -220,7 +215,7 @@ class Configuration(object):
'value': self.get_basic_auth_token()
},
{{/isBasic}}{{#isOAuth}}
'{{name}}':
'{{name}}':
{
'type': 'oauth2',
'in': 'header',

View File

@ -4,7 +4,6 @@
from __future__ import absolute_import
import sys
import io
import json
import ssl
@ -13,7 +12,8 @@ import logging
import re
# python 2 and python 3 compatibility library
from six import iteritems
from six import PY3
from six.moves.urllib.parse import urlencode
from .configuration import Configuration
@ -22,13 +22,6 @@ try:
except ImportError:
raise ImportError('Swagger python client requires urllib3.')
try:
# for python3
from urllib.parse import urlencode
except ImportError:
# for python2
from urllib import urlencode
logger = logging.getLogger(__name__)
@ -100,7 +93,7 @@ class RESTClientObject(object):
:param headers: http request headers
:param body: request json body, for `application/json`
:param post_params: request post parameters,
`application/x-www-form-urlencode`
`application/x-www-form-urlencoded`
and `multipart/form-data`
"""
method = method.upper()
@ -155,11 +148,11 @@ class RESTClientObject(object):
# In the python 3, the response.data is bytes.
# we need to decode it to string.
if sys.version_info > (3,):
if PY3:
r.data = r.data.decode('utf8')
# log response body
logger.debug("response body: %s" % r.data)
logger.debug("response body: %s", r.data)
if r.status not in range(200, 206):
raise ApiException(http_resp=r)

View File

@ -178,7 +178,7 @@ class RESTClientObject(object):
r.data = r.data.decode('utf8')
# log response body
logger.debug("response body: %s" % r.data)
logger.debug("response body: %s", r.data)
if r.status not in range(200, 206):
raise ApiException(http_resp=r)

View File

@ -5,7 +5,7 @@ This Python package is automatically generated by the [Swagger Codegen](https://
- API version: 1.0.0
- Package version: 1.0.0
- Build date: 2016-08-22T17:54:52.358+08:00
- Build date: 2016-08-27T14:30:36.450+03:00
- Build package: class io.swagger.codegen.languages.PythonClientCodegen
## Requirements.
@ -46,6 +46,7 @@ import petstore_api
Please follow the [installation procedure](#installation--usage) and then run the following:
```python
from __future__ import print_function
import time
import petstore_api
from petstore_api.rest import ApiException
@ -59,7 +60,7 @@ try:
api_response = api_instance.test_client_model(body)
pprint(api_response)
except ApiException as e:
print "Exception when calling FakeApi->test_client_model: %s\n" % e
print("Exception when calling FakeApi->test_client_model: %s\n" % e)
```

View File

@ -16,6 +16,7 @@ To test \"client\" model
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -30,7 +31,7 @@ try:
api_response = api_instance.test_client_model(body)
pprint(api_response)
except ApiException as e:
print "Exception when calling FakeApi->test_client_model: %s\n" % e
print("Exception when calling FakeApi->test_client_model: %s\n" % e)
```
### Parameters
@ -63,6 +64,7 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -92,7 +94,7 @@ try:
# Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
api_instance.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, date=date, date_time=date_time, password=password)
except ApiException as e:
print "Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e
print("Exception when calling FakeApi->test_endpoint_parameters: %s\n" % e)
```
### Parameters
@ -135,6 +137,7 @@ To test enum parameters
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -155,7 +158,7 @@ try:
# To test enum parameters
api_instance.test_enum_parameters(enum_form_string_array=enum_form_string_array, enum_form_string=enum_form_string, enum_header_string_array=enum_header_string_array, enum_header_string=enum_header_string, enum_query_string_array=enum_query_string_array, enum_query_string=enum_query_string, enum_query_integer=enum_query_integer, enum_query_double=enum_query_double)
except ApiException as e:
print "Exception when calling FakeApi->test_enum_parameters: %s\n" % e
print("Exception when calling FakeApi->test_enum_parameters: %s\n" % e)
```
### Parameters

View File

@ -23,6 +23,7 @@ Add a new pet to the store
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -39,7 +40,7 @@ try:
# Add a new pet to the store
api_instance.add_pet(body)
except ApiException as e:
print "Exception when calling PetApi->add_pet: %s\n" % e
print("Exception when calling PetApi->add_pet: %s\n" % e)
```
### Parameters
@ -72,6 +73,7 @@ Deletes a pet
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -89,7 +91,7 @@ try:
# Deletes a pet
api_instance.delete_pet(pet_id, api_key=api_key)
except ApiException as e:
print "Exception when calling PetApi->delete_pet: %s\n" % e
print("Exception when calling PetApi->delete_pet: %s\n" % e)
```
### Parameters
@ -123,6 +125,7 @@ Multiple status values can be provided with comma separated strings
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -140,7 +143,7 @@ try:
api_response = api_instance.find_pets_by_status(status)
pprint(api_response)
except ApiException as e:
print "Exception when calling PetApi->find_pets_by_status: %s\n" % e
print("Exception when calling PetApi->find_pets_by_status: %s\n" % e)
```
### Parameters
@ -173,6 +176,7 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -190,7 +194,7 @@ try:
api_response = api_instance.find_pets_by_tags(tags)
pprint(api_response)
except ApiException as e:
print "Exception when calling PetApi->find_pets_by_tags: %s\n" % e
print("Exception when calling PetApi->find_pets_by_tags: %s\n" % e)
```
### Parameters
@ -223,6 +227,7 @@ Returns a single pet
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -242,7 +247,7 @@ try:
api_response = api_instance.get_pet_by_id(pet_id)
pprint(api_response)
except ApiException as e:
print "Exception when calling PetApi->get_pet_by_id: %s\n" % e
print("Exception when calling PetApi->get_pet_by_id: %s\n" % e)
```
### Parameters
@ -275,6 +280,7 @@ Update an existing pet
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -291,7 +297,7 @@ try:
# Update an existing pet
api_instance.update_pet(body)
except ApiException as e:
print "Exception when calling PetApi->update_pet: %s\n" % e
print("Exception when calling PetApi->update_pet: %s\n" % e)
```
### Parameters
@ -324,6 +330,7 @@ Updates a pet in the store with form data
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -342,7 +349,7 @@ try:
# Updates a pet in the store with form data
api_instance.update_pet_with_form(pet_id, name=name, status=status)
except ApiException as e:
print "Exception when calling PetApi->update_pet_with_form: %s\n" % e
print("Exception when calling PetApi->update_pet_with_form: %s\n" % e)
```
### Parameters
@ -377,6 +384,7 @@ uploads an image
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -396,7 +404,7 @@ try:
api_response = api_instance.upload_file(pet_id, additional_metadata=additional_metadata, file=file)
pprint(api_response)
except ApiException as e:
print "Exception when calling PetApi->upload_file: %s\n" % e
print("Exception when calling PetApi->upload_file: %s\n" % e)
```
### Parameters

View File

@ -19,6 +19,7 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -32,7 +33,7 @@ try:
# Delete purchase order by ID
api_instance.delete_order(order_id)
except ApiException as e:
print "Exception when calling StoreApi->delete_order: %s\n" % e
print("Exception when calling StoreApi->delete_order: %s\n" % e)
```
### Parameters
@ -65,6 +66,7 @@ Returns a map of status codes to quantities
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -83,7 +85,7 @@ try:
api_response = api_instance.get_inventory()
pprint(api_response)
except ApiException as e:
print "Exception when calling StoreApi->get_inventory: %s\n" % e
print("Exception when calling StoreApi->get_inventory: %s\n" % e)
```
### Parameters
@ -113,6 +115,7 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -127,7 +130,7 @@ try:
api_response = api_instance.get_order_by_id(order_id)
pprint(api_response)
except ApiException as e:
print "Exception when calling StoreApi->get_order_by_id: %s\n" % e
print("Exception when calling StoreApi->get_order_by_id: %s\n" % e)
```
### Parameters
@ -160,6 +163,7 @@ Place an order for a pet
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -174,7 +178,7 @@ try:
api_response = api_instance.place_order(body)
pprint(api_response)
except ApiException as e:
print "Exception when calling StoreApi->place_order: %s\n" % e
print("Exception when calling StoreApi->place_order: %s\n" % e)
```
### Parameters

View File

@ -23,6 +23,7 @@ This can only be done by the logged in user.
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -36,7 +37,7 @@ try:
# Create user
api_instance.create_user(body)
except ApiException as e:
print "Exception when calling UserApi->create_user: %s\n" % e
print("Exception when calling UserApi->create_user: %s\n" % e)
```
### Parameters
@ -69,6 +70,7 @@ Creates list of users with given input array
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -82,7 +84,7 @@ try:
# Creates list of users with given input array
api_instance.create_users_with_array_input(body)
except ApiException as e:
print "Exception when calling UserApi->create_users_with_array_input: %s\n" % e
print("Exception when calling UserApi->create_users_with_array_input: %s\n" % e)
```
### Parameters
@ -115,6 +117,7 @@ Creates list of users with given input array
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -128,7 +131,7 @@ try:
# Creates list of users with given input array
api_instance.create_users_with_list_input(body)
except ApiException as e:
print "Exception when calling UserApi->create_users_with_list_input: %s\n" % e
print("Exception when calling UserApi->create_users_with_list_input: %s\n" % e)
```
### Parameters
@ -161,6 +164,7 @@ This can only be done by the logged in user.
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -174,7 +178,7 @@ try:
# Delete user
api_instance.delete_user(username)
except ApiException as e:
print "Exception when calling UserApi->delete_user: %s\n" % e
print("Exception when calling UserApi->delete_user: %s\n" % e)
```
### Parameters
@ -207,6 +211,7 @@ Get user by user name
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -221,7 +226,7 @@ try:
api_response = api_instance.get_user_by_name(username)
pprint(api_response)
except ApiException as e:
print "Exception when calling UserApi->get_user_by_name: %s\n" % e
print("Exception when calling UserApi->get_user_by_name: %s\n" % e)
```
### Parameters
@ -254,6 +259,7 @@ Logs user into the system
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -269,7 +275,7 @@ try:
api_response = api_instance.login_user(username, password)
pprint(api_response)
except ApiException as e:
print "Exception when calling UserApi->login_user: %s\n" % e
print("Exception when calling UserApi->login_user: %s\n" % e)
```
### Parameters
@ -303,6 +309,7 @@ Logs out current logged in user session
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -315,7 +322,7 @@ try:
# Logs out current logged in user session
api_instance.logout_user()
except ApiException as e:
print "Exception when calling UserApi->logout_user: %s\n" % e
print("Exception when calling UserApi->logout_user: %s\n" % e)
```
### Parameters
@ -345,6 +352,7 @@ This can only be done by the logged in user.
### Example
```python
from __future__ import print_statement
import time
import petstore_api
from petstore_api.rest import ApiException
@ -359,7 +367,7 @@ try:
# Updated user
api_instance.update_user(username, body)
except ApiException as e:
print "Exception when calling UserApi->update_user: %s\n" % e
print("Exception when calling UserApi->update_user: %s\n" % e)
```
### Parameters

View File

@ -19,17 +19,15 @@ Copyright 2016 SmartBear Software
"""
from __future__ import absolute_import
from . import models
from .rest import RESTClientObject
from .rest import ApiException
import os
import re
import sys
import urllib
import json
import mimetypes
import random
import tempfile
import threading
@ -37,22 +35,8 @@ from datetime import datetime
from datetime import date
# python 2 and python 3 compatibility library
from six import iteritems
try:
# for python3
from urllib.parse import quote
except ImportError:
# for python2
from urllib import quote
# special handling of `long` (python2 only)
try:
# Python 2
long
except NameError:
# Python 3
long = int
from six import PY3, integer_types, iteritems, text_type
from six.moves.urllib.parse import quote
from .configuration import Configuration
@ -113,7 +97,7 @@ class ApiClient(object):
body=None, post_params=None, files=None,
response_type=None, auth_settings=None, callback=None, _return_http_data_only=None):
# headers parameters
# header parameters
header_params = header_params or {}
header_params.update(self.default_headers)
if self.cookie:
@ -167,11 +151,10 @@ class ApiClient(object):
if callback:
callback(deserialized_data) if _return_http_data_only else callback((deserialized_data, response_data.status, response_data.getheaders()))
elif _return_http_data_only:
return ( deserialized_data );
return (deserialized_data)
else:
return (deserialized_data, response_data.status, response_data.getheaders())
def to_path_value(self, obj):
"""
Takes value and turn it into a string suitable for inclusion in
@ -201,9 +184,7 @@ class ApiClient(object):
:param obj: The data to serialize.
:return: The serialized form of data.
"""
types = (str, int, long, float, bool, tuple)
if sys.version_info < (3, 0):
types = types + (unicode,)
types = (str, float, bool, tuple) + tuple(integer_types) + (text_type,)
if isinstance(obj, type(None)):
return None
elif isinstance(obj, types):
@ -235,7 +216,7 @@ class ApiClient(object):
:param response: RESTResponse object to be deserialized.
:param response_type: class literal for
deserialzied object, or string of class name.
deserialized object, or string of class name.
:return: deserialized object.
"""
@ -277,14 +258,16 @@ class ApiClient(object):
# convert str to class
# for native types
if klass in ['int', 'long', 'float', 'str', 'bool',
if klass in ['int', 'float', 'str', 'bool',
"date", 'datetime', "object"]:
klass = eval(klass)
elif klass == 'long':
klass = int if PY3 else long
# for model types
else:
klass = eval('models.' + klass)
if klass in [int, long, float, str, bool]:
if klass in integer_types or klass in (float, str, bool):
return self.__deserialize_primitive(data, klass)
elif klass == object:
return self.__deserialize_object(data)
@ -339,7 +322,7 @@ class ApiClient(object):
header_params, body,
post_params, files,
response_type, auth_settings,
callback,_return_http_data_only))
callback, _return_http_data_only))
thread.start()
return thread

View File

@ -23,19 +23,14 @@
"""
from __future__ import absolute_import
import base64
import urllib3
try:
import httplib
except ImportError:
# for python3
import http.client as httplib
import urllib3
import sys
import logging
from six import iteritems
from six.moves import http_client as httplib
def singleton(cls, *args, **kw):
@ -229,7 +224,7 @@ class Configuration(object):
'value': self.get_api_key_with_prefix('api_key')
},
'petstore_auth':
'petstore_auth':
{
'type': 'oauth2',
'in': 'header',

View File

@ -24,7 +24,6 @@
from __future__ import absolute_import
import sys
import io
import json
import ssl
@ -33,7 +32,8 @@ import logging
import re
# python 2 and python 3 compatibility library
from six import iteritems
from six import PY3
from six.moves.urllib.parse import urlencode
from .configuration import Configuration
@ -42,13 +42,6 @@ try:
except ImportError:
raise ImportError('Swagger python client requires urllib3.')
try:
# for python3
from urllib.parse import urlencode
except ImportError:
# for python2
from urllib import urlencode
logger = logging.getLogger(__name__)
@ -120,7 +113,7 @@ class RESTClientObject(object):
:param headers: http request headers
:param body: request json body, for `application/json`
:param post_params: request post parameters,
`application/x-www-form-urlencode`
`application/x-www-form-urlencoded`
and `multipart/form-data`
"""
method = method.upper()
@ -175,11 +168,11 @@ class RESTClientObject(object):
# In the python 3, the response.data is bytes.
# we need to decode it to string.
if sys.version_info > (3,):
if PY3:
r.data = r.data.decode('utf8')
# log response body
logger.debug("response body: %s" % r.data)
logger.debug("response body: %s", r.data)
if r.status not in range(200, 206):
raise ApiException(http_resp=r)