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)