Browse Source

Add `JSON_STRICT` config option

Allow flask to raise an error rather than return
data that is not JSON specification compliant.

Useful for edge cases such as `NaN` or `Infinity`, for which
the replacement value is application-dependent.
pull/2832/head
Andy Boughton 6 years ago
parent
commit
bf47bd574e
No known key found for this signature in database
GPG Key ID: B82F55E6950590AA
  1. 8
      docs/config.rst
  2. 1
      flask/app.py
  3. 7
      flask/json/__init__.py
  4. 8
      tests/test_basic.py
  5. 2
      tests/test_helpers.py

8
docs/config.rst

@ -315,6 +315,14 @@ The following configuration values are used internally by Flask:
Default: ``True``
.. py:data:: JSON_STRICT
Raise an error when encountering values that cannot be serialized in a
strictly JSON compliant manner (such as ``NaN`` and ``Infinity``),
rather than encoding them as such.
Default: ``False``
.. py:data:: JSONIFY_PRETTYPRINT_REGULAR
``jsonify`` responses will be output with newlines, spaces, and indentation

1
flask/app.py

@ -304,6 +304,7 @@ class Flask(_PackageBoundObject):
'PREFERRED_URL_SCHEME': 'http',
'JSON_AS_ASCII': True,
'JSON_SORT_KEYS': True,
'JSON_STRICT': False,
'JSONIFY_PRETTYPRINT_REGULAR': False,
'JSONIFY_MIMETYPE': 'application/json',
'TEMPLATES_AUTO_RELOAD': None,

7
flask/json/__init__.py

@ -102,6 +102,9 @@ def _dump_arg_defaults(kwargs):
if not current_app.config['JSON_AS_ASCII']:
kwargs.setdefault('ensure_ascii', False)
if current_app.config['JSON_STRICT']:
kwargs.setdefault('allow_nan', False)
kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])
else:
kwargs.setdefault('sort_keys', True)
@ -173,6 +176,10 @@ def dumps(obj, **kwargs):
default which coerce into unicode strings automatically. That behavior by
default is controlled by the ``JSON_AS_ASCII`` configuration variable
and can be overridden by the simplejson ``ensure_ascii`` parameter.
If the ``JSON_STRICT`` config parameter is set to True, this function will
raise a :exc:`ValueError` if it encounters values that cannot be represented in
a JSON specification compliant manner.
"""
_dump_arg_defaults(kwargs)
encoding = kwargs.pop('encoding', None)

8
tests/test_basic.py

@ -1298,6 +1298,14 @@ def test_jsonify_prettyprint(app, req_ctx):
assert rv.data == pretty_response
@pytest.mark.parametrize('test_value', [float('nan'), float('Infinity')])
def test_json_strict(app, req_ctx, test_value):
app.config.update({'JSON_STRICT': True})
with pytest.raises(ValueError) as e:
flask.jsonify(test_value)
assert 'not JSON compliant' in str(e.value)
def test_jsonify_mimetype(app, req_ctx):
app.config.update({"JSONIFY_MIMETYPE": 'application/vnd.api+json'})
msg = {

2
tests/test_helpers.py

@ -155,7 +155,7 @@ class TestJSON(object):
rv = flask.json.load(out)
assert rv == test_data
@pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, 's', "longer string", True, False, None])
@pytest.mark.parametrize('test_value', [0, -1, 1, 23, 3.14, float('Infinity'), 's', "longer string", True, False, None])
def test_jsonify_basic_types(self, test_value, app, client):
"""Test jsonify with basic types."""

Loading…
Cancel
Save