Skip to content

Commit 0fda4ac

Browse files
committed
Fix escape_string doesn't accept unicode on Python 2
fixes PyMySQL#415
1 parent f427d5a commit 0fda4ac

File tree

4 files changed

+30
-5
lines changed

4 files changed

+30
-5
lines changed

pymysql/_compat.py

+3
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,15 @@
77
CPYTHON = not PYPY and not JYTHON and not IRONPYTHON
88

99
if PY2:
10+
import __builtin__
1011
range_type = xrange
1112
text_type = unicode
1213
long_type = long
1314
str_type = basestring
15+
unichr = __builtin__.unichr
1416
else:
1517
range_type = range
1618
text_type = str
1719
long_type = int
1820
str_type = str
21+
unichr = chr

pymysql/converters.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
from ._compat import PY2, text_type, long_type, JYTHON, IRONPYTHON
1+
from ._compat import PY2, text_type, long_type, JYTHON, IRONPYTHON, unichr
22

3-
import sys
4-
import binascii
53
import datetime
64
from decimal import Decimal
75
import time
@@ -57,7 +55,7 @@ def escape_int(value, mapping=None):
5755
def escape_float(value, mapping=None):
5856
return ('%.15g' % value)
5957

60-
_escape_table = [chr(x) for x in range(128)]
58+
_escape_table = [unichr(x) for x in range(128)]
6159
_escape_table[0] = u'\\0'
6260
_escape_table[ord('\\')] = u'\\\\'
6361
_escape_table[ord('\n')] = u'\\n'
@@ -80,7 +78,7 @@ def escape_string(value, mapping=None):
8078
Value should be bytes or unicode.
8179
"""
8280
if isinstance(value, unicode):
83-
return escape_unicode(value)
81+
return _escape_unicode(value)
8482
assert isinstance(value, (bytes, bytearray))
8583
value = value.replace('\\', '\\\\')
8684
value = value.replace('\0', '\\0')

pymysql/tests/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from pymysql.tests.test_SSCursor import *
77
from pymysql.tests.test_load_local import *
88
from pymysql.tests.test_optionfile import *
9+
from pymysql.tests.test_converters import *
910

1011
from pymysql.tests.thirdparty import *
1112

pymysql/tests/test_converters.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from unittest import TestCase
2+
3+
from pymysql._compat import PY2
4+
from pymysql import converters
5+
6+
7+
__all__ = ["TestConverter"]
8+
9+
10+
class TestConverter(TestCase):
11+
12+
def test_escape_string(self):
13+
self.assertEqual(
14+
converters.escape_string(u"foo\nbar"),
15+
u"foo\\nbar"
16+
)
17+
18+
if PY2:
19+
def test_escape_string_bytes(self):
20+
self.assertEqual(
21+
converters.escape_string(b"foo\nbar"),
22+
b"foo\\nbar"
23+
)

0 commit comments

Comments
 (0)