enable setting the json_encoder
This commit is contained in:
parent
9ae4eba986
commit
83e90b1e1a
2 changed files with 38 additions and 1 deletions
|
|
@ -31,6 +31,8 @@ except ImportError:
|
||||||
from django.utils import simplejson as json
|
from django.utils import simplejson as json
|
||||||
except ImportError:
|
except ImportError:
|
||||||
json_available = False
|
json_available = False
|
||||||
|
if json_available:
|
||||||
|
json_encoder = json.JSONEncoder
|
||||||
|
|
||||||
|
|
||||||
from werkzeug import Headers, wrap_file, cached_property
|
from werkzeug import Headers, wrap_file, cached_property
|
||||||
|
|
@ -104,7 +106,8 @@ def jsonify(*args, **kwargs):
|
||||||
if __debug__:
|
if __debug__:
|
||||||
_assert_have_json()
|
_assert_have_json()
|
||||||
return current_app.response_class(json.dumps(dict(*args, **kwargs),
|
return current_app.response_class(json.dumps(dict(*args, **kwargs),
|
||||||
indent=None if request.is_xhr else 2), mimetype='application/json')
|
indent=None if request.is_xhr else 2, cls=json_encoder),
|
||||||
|
mimetype='application/json')
|
||||||
|
|
||||||
|
|
||||||
def make_response(*args):
|
def make_response(*args):
|
||||||
|
|
|
||||||
|
|
@ -707,6 +707,40 @@ class JSONTestCase(unittest.TestCase):
|
||||||
assert rv.status_code == 200
|
assert rv.status_code == 200
|
||||||
assert rv.data == u'정상처리'.encode('utf-8')
|
assert rv.data == u'정상처리'.encode('utf-8')
|
||||||
|
|
||||||
|
def test_json_with_object(self):
|
||||||
|
class DataObject(object):
|
||||||
|
def __init__(self):
|
||||||
|
self.attr_a = 'a'
|
||||||
|
self.attr_b = 'b'
|
||||||
|
d = DataObject()
|
||||||
|
|
||||||
|
app = flask.Flask(__name__)
|
||||||
|
@app.route('/get')
|
||||||
|
def get():
|
||||||
|
return flask.jsonify(arg=d)
|
||||||
|
|
||||||
|
c = app.test_client()
|
||||||
|
rv = c.get('/get')
|
||||||
|
self.assertEquals(500, rv.status_code)
|
||||||
|
|
||||||
|
import flask.helpers as helpers
|
||||||
|
old_encoder = helpers.json_encoder
|
||||||
|
try:
|
||||||
|
class ExtendedJSONEncoder(helpers.json_encoder):
|
||||||
|
def default(self, o):
|
||||||
|
if isinstance(o, DataObject):
|
||||||
|
return {'attr_a': o.attr_a, 'attr_b': o.attr_b}
|
||||||
|
else:
|
||||||
|
return super(json_encoder, self).default(o)
|
||||||
|
helpers.json_encoder = ExtendedJSONEncoder
|
||||||
|
|
||||||
|
rv = c.get('/get')
|
||||||
|
self.assertEquals(200, rv.status_code)
|
||||||
|
self.assertEquals(flask.json.loads(rv.data),
|
||||||
|
{'arg': {'attr_a': 'a', 'attr_b': 'b'}})
|
||||||
|
finally:
|
||||||
|
helpers.json_encoder = old_encoder
|
||||||
|
|
||||||
if not has_encoding('euc-kr'):
|
if not has_encoding('euc-kr'):
|
||||||
test_modified_url_encoding = None
|
test_modified_url_encoding = None
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue