Skip to content

Commit

Permalink
Handle non-unicode binary data (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
gmr committed Jul 16, 2015
1 parent 487fece commit f9ac424
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
10 changes: 8 additions & 2 deletions consulate/api/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,10 @@ def _demarshal(self, body):
return None
try:
if utils.PYTHON3 and isinstance(body, bytes):
body = body.decode('utf-8')
try:
body = body.decode('utf-8')
except UnicodeDecodeError:
pass
value = json.loads(body, encoding='utf-8')
except (TypeError, ValueError):
return body
Expand All @@ -143,7 +146,10 @@ def _demarshal(self, body):
try:
row['Value'] = base64.b64decode(row['Value'])
if isinstance(row['Value'], bytes):
row['Value'] = row['Value'].decode('utf-8')
try:
row['Value'] = row['Value'].decode('utf-8')
except UnicodeDecodeError:
pass
except TypeError:
pass
if isinstance(value, list) and len(value) == 1:
Expand Down
20 changes: 16 additions & 4 deletions consulate/api/kv.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,16 @@ def _get_modify_index(self, item, value, replace):
index = response.body.get('ModifyIndex')
rvalue = response.body.get('Value')
if isinstance(rvalue, bytes):
rvalue = rvalue.encode('utf-8')
if utils.PYTHON3:
try:
rvalue = str(rvalue, 'utf-8')
except UnicodeDecodeError:
pass
else:
try:
rvalue = rvalue.encode('utf-8')
except UnicodeDecodeError:
pass
if rvalue == value:
return None
if not replace:
Expand All @@ -353,12 +362,15 @@ def _prepare_value(value):
"""
if utils.is_string(value):
if utils.PYTHON3:
value = value.encode('utf-8')
try:
value = str(value, 'utf-8')
except UnicodeDecodeError:
pass
elif not isinstance(value, unicode):
try:
value.decode('ascii')
value.decode('utf-8')
except UnicodeDecodeError:
value = value.decode('utf-8')
pass
return value

def _set_item(self, item, value, flags=None, replace=True):
Expand Down

0 comments on commit f9ac424

Please sign in to comment.