Use Werkzeug's JSONMixin class and update tests
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Flask's JSONMixin class was moved to Werkzeug>=0.15
authored by EtiennePelletier · committed by David Lord · parent d0bfb06 · 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.
Trailers
- Co-authored-by: Jeffrey Eliasen <jeff@jke.net>
Diff stats
5 files+18 added−131 removed
- tests:+5 added−43 removed
- other:+13 added−88 removed
Provenance
- Commit
8590d65- Tree
8a35633- Author
EtiennePelletier <etpelletier93@hotmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
d0bfb06
5 files changed+18 added−131 removed
modified:flask/wrappers.py+4 added-86 removed
9 unmodified lines10 """11 12 from werkzeug.exceptions import BadRequest13 from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase14+from werkzeug.wrappers.json import JSONMixin as _JSONMixin15 16 from flask import json17 from flask.globals import current_app18 19 19-class JSONMixin(object):20- """Common mixin for both request and response objects to provide JSON21- parsing capabilities.20+class JSONMixin(_JSONMixin):21+ json_module = json22 23- .. versionadded:: 1.024- """25-26- _cached_json = (Ellipsis, Ellipsis)27-28- @property29- def is_json(self):30- """Check if the mimetype indicates JSON data, either31- :mimetype:`application/json` or :mimetype:`application/*+json`.32-33- .. versionadded:: 0.1134- """35- mt = self.mimetype36- return (37- mt == "application/json"38- or (mt.startswith("application/"))39- and mt.endswith("+json")40- )41-42- @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()49-50- def _get_data_for_json(self, cache):51- return self.get_data(cache=cache)52-53- 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.59-60- :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]68-69- if not (force or self.is_json):70- return None71-72- data = self._get_data_for_json(cache=cache)73-74- 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)90-91- return rv92-23 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.98-99- .. 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.103-104- .. 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))26 27 raise BadRequest()28 108 unmodified linesmodified:tests/test_helpers.py+5 added-43 removed
90 unmodified lines91 data = json.dumps(value).encode(encoding)92 assert json.detect_encoding(data) == encoding93 assert json.loads(data) == value94 95- 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)102-103- 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)110-111- 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"117-118- 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"] = False99 100 @app.route("/json", methods=["POST"])101 def post_json():1 unmodified line103 return None104 105 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 == debug109 133- 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"] = False138-139- @app.route("/json", methods=["POST"])140- def post_json():141- flask.request.get_json()142- return None143-144- 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.data147-110 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 linesmodified:CHANGES.rst+7 added
7 unmodified lines8 -------------9 10 Unreleased11 12+- 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 in10 unmodified lines28 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`36 37 .. _#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/312543 44 45 Version 1.0.346 -------------941 unmodified linesmodified:setup.py+1 added-1 removed
34 unmodified lines35 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 linesmodified:tox.ini+1 added-1 removed
12 unmodified lines13 greenlet14 blinker15 python-dotenv16 17- lowest: Werkzeug==0.1417+ lowest: Werkzeug==0.1518 lowest: Jinja2==2.1019 lowest: itsdangerous==0.2420 lowest: Click==5.121 53 unmodified lines