Skip to content

Commit 087215b

Browse files
authored
Merge pull request #5 from gunthercox/chatterbot_352
Support saving unescaped unicode characters to the database
2 parents 9bcca52 + e4c37c5 commit 087215b

3 files changed

Lines changed: 34 additions & 12 deletions

File tree

jsondb/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from .db import Database
22

3-
__version__ = "0.1.2"
4-
__maintainer__ = "Gunther Cox"
5-
__email__ = "gunthercx@gmail.com"
3+
__version__ = '0.1.3'
4+
__maintainer__ = 'Gunther Cox'
5+
__email__ = 'gunthercx@gmail.com'
66

jsondb/compat.py

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1+
import codecs
12
import sys
3+
import io
24

3-
'''
4-
Use the faster cjson library if it is available
5-
'''
65

76
try:
7+
# Use the faster cjson library if it is available
88
import cjson as json
99

1010
json_encode = json.encode
@@ -18,17 +18,19 @@
1818

1919

2020
def encode(value):
21-
return json_encode(value)
21+
value = json_encode(value, ensure_ascii=False)
22+
if sys.version < '3':
23+
return unicode(value)
24+
return value
2225

2326

2427
def decode(value):
25-
return json_decode(value)
28+
return json_decode(value, encoding='utf-8')
2629

2730

2831
if sys.version < '3':
2932

3033
# Python 2 and 3 unicode string compatability
31-
import codecs
3234
def u(x):
3335
return codecs.unicode_escape_decode(x)[0]
3436

@@ -42,3 +44,23 @@ def u(x):
4244
# Dictionary iteration compatibility
4345
def iteritems(dictionary):
4446
return dictionary.items()
47+
48+
49+
def open_file_for_reading(*args, **kwargs):
50+
if sys.version < '3':
51+
kwargs['mode'] = 'rb+'
52+
else:
53+
kwargs['encoding'] = 'utf-8'
54+
kwargs['mode'] = 'r+'
55+
56+
return io.open(*args, **kwargs)
57+
58+
59+
def open_file_for_writing(*args, **kwargs):
60+
if sys.version < '3':
61+
kwargs['mode'] = 'w+'
62+
else:
63+
kwargs['encoding'] = 'utf-8'
64+
kwargs['mode'] = 'w+'
65+
66+
return io.open(*args, **kwargs)

jsondb/file_writer.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from .compat import decode, encode
1+
from .compat import decode, encode, open_file_for_reading, open_file_for_writing
22

33

44
def read_data(file_path):
@@ -9,7 +9,7 @@ def read_data(file_path):
99
if not is_valid(file_path):
1010
write_data(file_path, {})
1111

12-
db = open(file_path, "r+")
12+
db = open_file_for_reading(file_path)
1313
content = db.read()
1414

1515
obj = decode(content)
@@ -22,7 +22,7 @@ def write_data(path, obj):
2222
"""
2323
Writes to a file and returns the updated file content.
2424
"""
25-
with open(path, "w+") as db:
25+
with open_file_for_writing(path) as db:
2626
db.write(encode(obj))
2727

2828
return obj

0 commit comments

Comments
 (0)