Browse Source

Improve compression by removing whitespace from separators when using jsonify() and JSONIFY_PRETTYPRINT_REGULAR is False.

Commit includes Changelog entry and two new tests in test_basic.py.
pull/1217/head
Gilman Callsen 10 years ago committed by Markus Unterwaditzer
parent
commit
d425279650
  1. 3
      CHANGES
  2. 9
      flask/json.py
  3. 28
      tests/test_basic.py

3
CHANGES

@ -51,6 +51,9 @@ Version 1.0
loading.
- Ported testsuite to py.test.
- 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

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
with ``X-Requested-With: XMLHttpRequest`` to simplify debugging unless
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
"""
indent = None
separators = (',', ':')
if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] \
and not request.is_xhr:
indent = 2
separators = (', ', ': ')
return current_app.response_class(dumps(dict(*args, **kwargs),
indent=indent),
indent=indent, separators=separators),
mimetype='application/json')

28
tests/test_basic.py

@ -959,6 +959,34 @@ def test_make_response_with_response_instance():
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():
app = flask.Flask(__name__)

Loading…
Cancel
Save