Skip to content

Commit a5b228a

Browse files
committed
better handling of bytestrings in _escape
Fixes elastic#627
1 parent 9320ee7 commit a5b228a

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

elasticsearch/client/utils.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,13 @@ def _escape(value):
2626
elif isinstance(value, bool):
2727
value = str(value).lower()
2828

29+
# don't decode bytestrings
30+
elif isinstance(value, bytes):
31+
return value
32+
2933
# encode strings to utf-8
3034
if isinstance(value, string_types):
31-
try:
32-
return value.encode('utf-8')
33-
except UnicodeDecodeError:
34-
# Python 2 and str, no need to re-encode
35-
pass
35+
return value.encode('utf-8')
3636

3737
return str(value)
3838

test_elasticsearch/test_client/test_utils.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# -*- coding: utf-8 -*-
22
from __future__ import unicode_literals
33

4-
from elasticsearch.client.utils import _make_path
4+
from elasticsearch.client.utils import _make_path, _escape
55
from elasticsearch.compat import PY2
66

77
from ..test_cases import TestCase, SkipTest
@@ -17,3 +17,24 @@ def test_handles_utf_encoded_string(self):
1717
id = "中文".encode('utf-8')
1818
self.assertEquals('/some-index/type/%E4%B8%AD%E6%96%87', _make_path('some-index', 'type', id))
1919

20+
21+
class TestEscape(TestCase):
22+
def test_handles_ascii(self):
23+
string = "abc123"
24+
self.assertEquals(
25+
b'abc123',
26+
_escape(string)
27+
)
28+
def test_handles_unicode(self):
29+
string = "中文"
30+
self.assertEquals(
31+
b'\xe4\xb8\xad\xe6\x96\x87',
32+
_escape(string)
33+
)
34+
35+
def test_handles_bytestring(self):
36+
string = b'celery-task-meta-c4f1201f-eb7b-41d5-9318-a75a8cfbdaa0'
37+
self.assertEquals(
38+
string,
39+
_escape(string)
40+
)

0 commit comments

Comments
 (0)