8
8
:copyright: (c) 2012 by Armin Ronacher.
9
9
:license: BSD, see LICENSE for more details.
10
10
"""
11
+ import io
11
12
import uuid
12
13
from datetime import datetime
13
14
from .globals import current_app , request
14
- from ._compat import text_type
15
+ from ._compat import text_type , PY2
15
16
16
17
from werkzeug .http import http_date
17
18
33
34
'jsonify' ]
34
35
35
36
37
+ def _wrap_reader_for_text (fp , encoding ):
38
+ if isinstance (fp .read (0 ), bytes ):
39
+ fp = io .TextIOWrapper (io .BufferedReader (fp ), encoding )
40
+ return fp
41
+
42
+
43
+ def _wrap_writer_for_text (fp , encoding ):
44
+ try :
45
+ fp .write ('' )
46
+ except TypeError :
47
+ fp = io .TextIOWrapper (fp , encoding )
48
+ return fp
49
+
50
+
36
51
class JSONEncoder (_json .JSONEncoder ):
37
52
"""The default Flask JSON encoder. This one extends the default simplejson
38
53
encoder by also supporting ``datetime`` objects, ``UUID`` as well as
@@ -100,13 +115,20 @@ def dumps(obj, **kwargs):
100
115
and can be overriden by the simplejson ``ensure_ascii`` parameter.
101
116
"""
102
117
_dump_arg_defaults (kwargs )
103
- return _json .dumps (obj , ** kwargs )
118
+ encoding = kwargs .pop ('encoding' , None )
119
+ rv = _json .dumps (obj , ** kwargs )
120
+ if encoding is not None and isinstance (rv , text_type ):
121
+ rv = rv .encode (encoding )
122
+ return rv
104
123
105
124
106
125
def dump (obj , fp , ** kwargs ):
107
126
"""Like :func:`dumps` but writes into a file object."""
108
127
_dump_arg_defaults (kwargs )
109
- return _json .dump (obj , fp , ** kwargs )
128
+ encoding = kwargs .pop ('encoding' , None )
129
+ if encoding is not None :
130
+ fp = _wrap_writer_for_text (fp , encoding )
131
+ _json .dump (obj , fp , ** kwargs )
110
132
111
133
112
134
def loads (s , ** kwargs ):
@@ -115,13 +137,17 @@ def loads(s, **kwargs):
115
137
application on the stack.
116
138
"""
117
139
_load_arg_defaults (kwargs )
140
+ if isinstance (s , bytes ):
141
+ s = s .decode (kwargs .pop ('encoding' , None ) or 'utf-8' )
118
142
return _json .loads (s , ** kwargs )
119
143
120
144
121
145
def load (fp , ** kwargs ):
122
146
"""Like :func:`loads` but reads from a file object.
123
147
"""
124
148
_load_arg_defaults (kwargs )
149
+ if not PY2 :
150
+ fp = _wrap_reader_for_text (fp , kwargs .pop ('encoding' , None ) or 'utf-8' )
125
151
return _json .load (fp , ** kwargs )
126
152
127
153
@@ -148,7 +174,7 @@ def jsonify(*args, **kwargs):
148
174
to this function are the same as to the :class:`dict` constructor.
149
175
150
176
Example usage::
151
-
177
+
152
178
from flask import jsonify
153
179
154
180
@app.route('/_get_current_user')
0 commit comments