From b6bfbd3e08016da9865c3f433aa33ad32f31151f Mon Sep 17 00:00:00 2001 From: Cyril Roelandt Date: Fri, 17 Jan 2014 01:12:26 +0100 Subject: [PATCH] Python 3: Fix an str vs bytes issue in tempfile In Python 3, one cannot write: from tempfile import NamedTemporaryFile with NamedTemporaryFile() as f: f.write('foobar') The input of f.write() must be bytes. Encode it when necessary in middleware/auth_token.py, in a way that is compatible with Python 2. Change-Id: Ib60afbc5e01c35f59cd7c9b68bfedb10ad897ff9 --- keystoneclient/middleware/auth_token.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/keystoneclient/middleware/auth_token.py b/keystoneclient/middleware/auth_token.py index ff1135f2e..e442442b2 100644 --- a/keystoneclient/middleware/auth_token.py +++ b/keystoneclient/middleware/auth_token.py @@ -1316,7 +1316,8 @@ class AuthProtocol(object): if list_is_current: # Load the list from disk if required if not self._token_revocation_list: - with open(self.revoked_file_name, 'r') as f: + open_kwargs = {'encoding': 'utf-8'} if six.PY3 else {} + with open(self.revoked_file_name, 'r', **open_kwargs) as f: self._token_revocation_list = jsonutils.loads(f.read()) else: self.token_revocation_list = self.fetch_revocation_list() @@ -1334,6 +1335,10 @@ class AuthProtocol(object): with tempfile.NamedTemporaryFile(dir=self.signing_dirname, delete=False) as f: + # In Python2, encoding is slow so the following check avoids it if + # it is not absolutely necessary. + if isinstance(value, six.text_type): + value = value.encode('utf-8') f.write(value) os.rename(f.name, self.revoked_file_name)