Browse Source

Merge branch 'compressed-jsonify'

Fix #1203
pull/1217/head
Markus Unterwaditzer 10 years ago
parent
commit
a8c36fb3d8
  1. 3
      CHANGES
  2. 9
      flask/json.py
  3. 30
      tests/test_basic.py

3
CHANGES

@ -51,6 +51,9 @@ Version 1.0
loading. loading.
- Ported testsuite to py.test. - Ported testsuite to py.test.
- Deprecated ``request.json`` in favour of ``request.get_json()``. - Deprecated ``request.json`` in favour of ``request.get_json()``.
- Add "pretty" and "compressed" separators definitions in jsonify() method.
Reduces JSON response size when JSONIFY_PRETTYPRINT_REGULAR=False by removing
unnecessary white space included by default after separators.
Version 0.10.2 Version 0.10.2

9
flask/json.py

@ -227,15 +227,22 @@ def jsonify(*args, **kwargs):
This function's response will be pretty printed if it was not requested This function's response will be pretty printed if it was not requested
with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless
the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false. the ``JSONIFY_PRETTYPRINT_REGULAR`` config parameter is set to false.
Compressed (not pretty) formatting currently means no indents and no
spaces after separators.
.. versionadded:: 0.2 .. versionadded:: 0.2
""" """
indent = None indent = None
separators = (',', ':')
if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] \ if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] \
and not request.is_xhr: and not request.is_xhr:
indent = 2 indent = 2
separators = (', ', ': ')
return current_app.response_class(dumps(dict(*args, **kwargs), return current_app.response_class(dumps(dict(*args, **kwargs),
indent=indent), indent=indent, separators=separators),
mimetype='application/json') mimetype='application/json')

30
tests/test_basic.py

@ -959,6 +959,36 @@ def test_make_response_with_response_instance():
assert rv.headers['X-Foo'] == 'bar' assert rv.headers['X-Foo'] == 'bar'
def test_jsonify_no_prettyprint():
app = flask.Flask(__name__)
app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": False})
with app.test_request_context():
compressed_msg = b'{"msg":{"submsg":"W00t"},"msg2":"foobar"}'
uncompressed_msg = {
"msg": {
"submsg": "W00t"
},
"msg2": "foobar"
}
rv = flask.make_response(
flask.jsonify(uncompressed_msg), 200)
assert rv.data == compressed_msg
def test_jsonify_prettyprint():
app = flask.Flask(__name__)
app.config.update({"JSONIFY_PRETTYPRINT_REGULAR": True})
with app.test_request_context():
compressed_msg = {"msg":{"submsg":"W00t"},"msg2":"foobar"}
pretty_response =\
b'{\n "msg": {\n "submsg": "W00t"\n }, \n "msg2": "foobar"\n}'
rv = flask.make_response(
flask.jsonify(compressed_msg), 200)
assert rv.data == pretty_response
def test_url_generation(): def test_url_generation():
app = flask.Flask(__name__) app = flask.Flask(__name__)

Loading…
Cancel
Save