From 66040e0c9d0ad468ba59bc3bc6b100264a7d3096 Mon Sep 17 00:00:00 2001 From: Esteban Echeverry Date: Fri, 2 Jun 2017 12:12:07 -0500 Subject: [PATCH] Fix unicode errors in json.load method HTTPConnection returns bytes in Python 2. An explicit decoding is needed in Python 3 to ensure compatibility. --- lib/ansible/module_utils/lxd.py | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/lib/ansible/module_utils/lxd.py b/lib/ansible/module_utils/lxd.py index 5b7c17dd42d..e05e4d54d0a 100644 --- a/lib/ansible/module_utils/lxd.py +++ b/lib/ansible/module_utils/lxd.py @@ -27,23 +27,22 @@ # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +import socket +import ssl + from ansible.module_utils.urls import generic_urlparse from ansible.module_utils.six.moves.urllib.parse import urlparse - -try: - import json -except ImportError: - import simplejson as json +from ansible.module_utils.six.moves import http_client +from ansible.module_utils.six import PY2 # httplib/http.client connection using unix domain socket -import socket -import ssl +HTTPConnection = http_client.HTTPConnection +HTTPSConnection = http_client.HTTPSConnection try: - from httplib import HTTPConnection, HTTPSConnection + import json except ImportError: - # Python 3 - from http.client import HTTPConnection, HTTPSConnection + import simplejson as json class UnixHTTPConnection(HTTPConnection): @@ -110,7 +109,10 @@ class LXDClient(object): body = json.dumps(body_json) self.connection.request(method, url, body=body) resp = self.connection.getresponse() - resp_json = json.loads(resp.read()) + resp_data = resp.read() + if not PY2: + resp_data = resp_data.decode('utf-8') + resp_json = json.loads(resp_data) self.logs.append({ 'type': 'sent request', 'request': {'method': method, 'url': url, 'json': body_json, 'timeout': timeout},