Skip to content
Myr

Merge pull request #3181 from EtiennePelletier/Flask-3125

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Use Werkzeug's JSONMixin class (moved from Flask) and update tests

authored by David Lord · committed by GitHub · parents d0bfb06, 8590d65 · Browse files · 5 files+18 added−131 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+18 added−131 removed

  • tests:+5 added−43 removed
  • other:+13 added−88 removed

5 files+18 added−131 removed

modified:flask/wrappers.py+4 added-86 removed
9 unmodified lines
10"""1112from werkzeug.exceptions import BadRequest13from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase14from werkzeug.wrappers.json import JSONMixin as _JSONMixin1516from flask import json17from flask.globals import current_app181919class JSONMixin(object):20 """Common mixin for both request and response objects to provide JSON21 parsing capabilities.20class JSONMixin(_JSONMixin):21 json_module = json2223 .. versionadded:: 1.024 """2526 _cached_json = (Ellipsis, Ellipsis)2728 @property29 def is_json(self):30 """Check if the mimetype indicates JSON data, either31 :mimetype:`application/json` or :mimetype:`application/*+json`.3233 .. versionadded:: 0.1134 """35 mt = self.mimetype36 return (37 mt == "application/json"38 or (mt.startswith("application/"))39 and mt.endswith("+json")40 )4142 @property43 def json(self):44 """This will contain the parsed JSON data if the mimetype indicates45 JSON (:mimetype:`application/json`, see :meth:`is_json`), otherwise it46 will be ``None``.47 """48 return self.get_json()4950 def _get_data_for_json(self, cache):51 return self.get_data(cache=cache)5253 def get_json(self, force=False, silent=False, cache=True):54 """Parse and return the data as JSON. If the mimetype does not55 indicate JSON (:mimetype:`application/json`, see56 :meth:`is_json`), this returns ``None`` unless ``force`` is57 true. If parsing fails, :meth:`on_json_loading_failed` is called58 and its return value is used as the return value.5960 :param force: Ignore the mimetype and always try to parse JSON.61 :param silent: Silence parsing errors and return ``None``62 instead.63 :param cache: Store the parsed JSON to return for subsequent64 calls.65 """66 if cache and self._cached_json[silent] is not Ellipsis:67 return self._cached_json[silent]6869 if not (force or self.is_json):70 return None7172 data = self._get_data_for_json(cache=cache)7374 try:75 rv = json.loads(data)76 except ValueError as e:77 if silent:78 rv = None79 if cache:80 normal_rv, _ = self._cached_json81 self._cached_json = (normal_rv, rv)82 else:83 rv = self.on_json_loading_failed(e)84 if cache:85 _, silent_rv = self._cached_json86 self._cached_json = (rv, silent_rv)87 else:88 if cache:89 self._cached_json = (rv, rv)9091 return rv9223 def on_json_loading_failed(self, e):94 """Called if :meth:`get_json` parsing fails and isn't silenced. If95 this method returns a value, it is used as the return value for96 :meth:`get_json`. The default implementation raises a97 :class:`BadRequest` exception.9899 .. versionchanged:: 0.10100 Raise a :exc:`BadRequest` error instead of returning an error101 message as JSON. If you want that behavior you can add it by102 subclassing.103104 .. versionadded:: 0.8105 """106 if current_app is not None and current_app.debug:24 if current_app and current_app.debug:25 raise BadRequest("Failed to decode JSON object: {0}".format(e))2627 raise BadRequest()28
108 unmodified lines
modified:tests/test_helpers.py+5 added-43 removed
90 unmodified lines
91 data = json.dumps(value).encode(encoding)92 assert json.detect_encoding(data) == encoding93 assert json.loads(data) == value9495 def test_ignore_cached_json(self, app):96 with app.test_request_context(97 "/", method="POST", data="malformed", content_type="application/json"98 ):99 assert flask.request.get_json(silent=True, cache=True) is None100 with pytest.raises(BadRequest):101 flask.request.get_json(silent=False, cache=False)102103 def test_different_silent_on_bad_request(self, app):104 with app.test_request_context(105 "/", method="POST", data="malformed", content_type="application/json"106 ):107 assert flask.request.get_json(silent=True) is None108 with pytest.raises(BadRequest):109 flask.request.get_json(silent=False)110111 def test_different_silent_on_normal_request(self, app):112 with app.test_request_context("/", method="POST", json={"foo": "bar"}):113 silent_rv = flask.request.get_json(silent=True)114 normal_rv = flask.request.get_json(silent=False)115 assert silent_rv is normal_rv116 assert normal_rv["foo"] == "bar"117118 def test_post_empty_json_adds_exception_to_response_content_in_debug(119 self, app, client120 ):121 app.config["DEBUG"] = True95 @pytest.mark.parametrize("debug", (True, False))96 def test_bad_request_debug_message(self, app, client, debug):97 app.config["DEBUG"] = debug98 app.config["TRAP_BAD_REQUEST_ERRORS"] = False99100 @app.route("/json", methods=["POST"])101 def post_json():
1 unmodified line
103 return None104105 rv = client.post("/json", data=None, content_type="application/json")106 assert rv.status_code == 400131 assert b"Failed to decode JSON object" in rv.data107 contains = b"Failed to decode JSON object" in rv.data108 assert contains == debug109133 def test_post_empty_json_wont_add_exception_to_response_if_no_debug(134 self, app, client135 ):136 app.config["DEBUG"] = False137 app.config["TRAP_BAD_REQUEST_ERRORS"] = False138139 @app.route("/json", methods=["POST"])140 def post_json():141 flask.request.get_json()142 return None143144 rv = client.post("/json", data=None, content_type="application/json")145 assert rv.status_code == 400146 assert b"Failed to decode JSON object" not in rv.data147110 def test_json_bad_requests(self, app, client):111 @app.route("/json", methods=["POST"])112 def return_json():113 return flask.jsonify(foo=text_type(flask.request.get_json()))
926 unmodified lines
modified:CHANGES.rst+7 added
7 unmodified lines
8-------------910Unreleased1112- Bump minimum Werkzeug version to >= 0.15.13- Drop support for Python 3.4.14- :meth:`flask.RequestContext.copy` includes the current session15 object in the request context copy. This prevents ``session``16 pointing to an out-of-date object. (`#2935`_)17- Using built-in RequestContext, unprintable Unicode characters in
10 unmodified lines
28 by subclasses. :issue:`3138`29- :attr:`Flask.jinja_options` is a ``dict`` instead of an30 ``ImmutableDict`` to allow easier configuration. Changes must still31 be made before creating the environment. :pr:`3190`32- Flask's ``JSONMixin`` for the request and response wrappers was33 moved into Werkzeug. Use Werkzeug's version with Flask-specific34 support. This bumps the Werkzeug dependency to >= 0.15.35 :issue:`3125`3637.. _#2935: https://github.com/pallets/flask/issues/293538.. _#2957: https://github.com/pallets/flask/issues/295739.. _#2994: https://github.com/pallets/flask/pull/299440.. _#3059: https://github.com/pallets/flask/pull/305941.. _#3179: https://github.com/pallets/flask/pull/317942.. _#3125: https://github.com/pallets/flask/pull/3125434445Version 1.0.346-------------
941 unmodified lines
modified:setup.py+1 added-1 removed
34 unmodified lines
35 zip_safe=False,36 platforms="any",37 python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*",38 install_requires=[39 "Werkzeug>=0.14",39 "Werkzeug>=0.15",40 "Jinja2>=2.10.1",41 "itsdangerous>=0.24",42 "click>=5.1",43 ],
34 unmodified lines
modified:tox.ini+1 added-1 removed
12 unmodified lines
13 greenlet14 blinker15 python-dotenv1617 lowest: Werkzeug==0.1417 lowest: Werkzeug==0.1518 lowest: Jinja2==2.1019 lowest: itsdangerous==0.2420 lowest: Click==5.121
53 unmodified lines