From 62df6c669f2625582cea9602ed2ec4a4aca2948a Mon Sep 17 00:00:00 2001 From: Jamie Lennox Date: Mon, 5 Jan 2015 11:46:13 +1000 Subject: [PATCH] Handle HTTP byte returns in python 3 The returns from requests' response.content is a bytes type. Under python 3 this fails in error handling and string conversion. The response.text variable should be used to treat a response body as a string. Closes-Bug: #1407531 Change-Id: Ifd588b5f6820ef21beb186d88d0b3f1a267695aa --- glanceclient/common/http.py | 4 ++-- tests/test_http.py | 2 +- tests/utils.py | 9 ++++++++- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/glanceclient/common/http.py b/glanceclient/common/http.py index a2ade225..67fde158 100644 --- a/glanceclient/common/http.py +++ b/glanceclient/common/http.py @@ -226,7 +226,7 @@ class HTTPClient(object): if not resp.ok: LOG.debug("Request returned failure status %s." % resp.status_code) - raise exc.from_response(resp, resp.content) + raise exc.from_response(resp, resp.text) elif resp.status_code == requests.codes.MULTIPLE_CHOICES: raise exc.from_response(resp) @@ -239,7 +239,7 @@ class HTTPClient(object): body_iter = resp.iter_content(chunk_size=CHUNKSIZE) self.log_http_response(resp) else: - content = resp.content + content = resp.text self.log_http_response(resp, content) if content_type and content_type.startswith('application/json'): # Let's use requests json method, diff --git a/tests/test_http.py b/tests/test_http.py index 54e56e2c..985284e5 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -221,7 +221,7 @@ class TestClient(testtools.TestCase): def test_http_json(self): data = {"test": "json_request"} - fake = utils.FakeResponse({}, "OK") + fake = utils.FakeResponse({}, b"OK") def test_json(passed_data): """ diff --git a/tests/utils.py b/tests/utils.py index b2849e5f..845b1858 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -132,8 +132,15 @@ class FakeResponse(object): return self.body.read() return self.body + @property + def text(self): + if isinstance(self.content, six.binary_type): + return self.content.decode('utf-8') + + return self.content + def json(self, **kwargs): - return self.body and json.loads(self.content) or "" + return self.body and json.loads(self.text) or "" def iter_content(self, chunk_size=1, decode_unicode=False): while True: