clean up JSON code and docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent dbc70c9 · Browse files · 5 files·+91 added−83 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+91 added−83 removed
- tests:+1 added−1 removed
- other:+90 added−82 removed
Provenance
- Commit
e97253e- Tree
fdf01ce- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
dbc70c9
5 files changed+91 added−83 removed
modified:docs/testing.rst+12 added-13 removed
380 unmodified lines381 -----------------382 383 .. versionadded:: 1.0384 385-Flask has great support for JSON, and is a popular choice for building REST386-APIs. Testing both JSON requests and responses using the test client is very387-convenient::385+Flask has great support for JSON, and is a popular choice for building JSON386+APIs. Making requests with JSON data and examining JSON data in responses is387+very convenient::388 389- from flask import jsonify389+ from flask import request, jsonify390 391 @app.route('/api/auth')392 def auth():393 json_data = request.get_json()394 email = json_data['email']395 password = json_data['password']396-396 return jsonify(token=generate_token(email, password))397 398 with app.test_client() as c:400- email = 'john@example.com'401- password = 'secret'402- resp = c.post('/api/auth', json={'login': email, 'password': password})403-404- json_data = resp.get_json()399+ rv = c.post('/api/auth', json={400+ 'username': 'flask', 'password': 'secret'401+ })402+ json_data = rv.get_json()403 assert verify_token(email, json_data['token'])404 407-Note that if the ``json`` argument is provided then the test client will put408-JSON-serialized data in the request body, and also set the409-``Content-Type: application/json`` HTTP header.405+Passing the ``json`` argument in the test client methods sets the request data406+to the JSON-serialized object and sets the content type to407+``application/json``. You can get the JSON data from the request or response408+with ``get_json``.modified:flask/testing.py+7 added-5 removed
21 unmodified lines22 from urlparse import urlsplit as url_parse23 24 25 def make_test_environ_builder(26- app, path='/', base_url=None, subdomain=None, url_scheme=None, json=None,26+ app, path='/', base_url=None, subdomain=None, url_scheme=None,27 *args, **kwargs28 ):29 """Creates a new test builder with some application defaults thrown in."""30 22 unmodified lines53 sep = b'?' if isinstance(url.query, bytes) else '?'54 path += sep + url.query55 56 if 'json' in kwargs:57- if 'data' in kwargs:58- raise ValueError('Client cannot provide both `json` and `data`')57+ assert 'data' not in kwargs, (58+ "Client cannot provide both 'json' and 'data'."59+ )60 61+ # push a context so flask.json can use app's json attributes62+ with app.app_context():60- kwargs['data'] = json_dumps(kwargs.pop('json'))63+ kwargs['data'] = json_dumps(kwargs.pop('json'))64 62- # Only set Content-Type when not explicitly provided65 if 'content_type' not in kwargs:66 kwargs['content_type'] = 'application/json'67 68 return EnvironBuilder(path, base_url, *args, **kwargs)107 unmodified linesmodified:flask/wrappers.py+64 added-59 removed
6 unmodified lines7 8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11+from warnings import warn12 12-from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase13 from werkzeug.exceptions import BadRequest14+from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase15 15-from . import json16-from .globals import _app_ctx_stack16+from flask import json17+from flask.globals import current_app18 19 20 class JSONMixin(object):21 """Common mixin for both request and response objects to provide JSON22 parsing capabilities.23 23- .. versionadded:: 0.1224+ .. versionadded:: 1.025 """26 27+ _cached_json = Ellipsis28+29 @property30 def is_json(self):28- """Indicates if this request/response is in JSON format or not. By29- default it is considered to include JSON data if the mimetype is31+ """Check if the mimetype indicates JSON data, either32 :mimetype:`application/json` or :mimetype:`application/*+json`.33 32- .. versionadded:: 1.034+ .. versionadded:: 0.1135 """36 mt = self.mimetype35- if mt == 'application/json':36- return True37- if mt.startswith('application/') and mt.endswith('+json'):38- return True39- return False37+ return (38+ mt == 'application/json'39+ or (mt.startswith('application/')) and mt.endswith('+json')40+ )41 42 @property43 def json(self):43- """If this request/response is in JSON format then this property will44- contain the parsed JSON data. Otherwise it will be ``None``.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 46- The :meth:`get_json` method should be used instead.48+ .. deprecated:: 1.049+ Use :meth:`get_json` instead.50 """48- from warnings import warn51 warn(DeprecationWarning(50- 'json is deprecated. Use get_json() instead.'), stacklevel=2)52+ "'json' is deprecated. Use 'get_json()' instead."53+ ), stacklevel=2)54 return self.get_json()55 56 def _get_data_for_json(self, cache):54- getter = getattr(self, 'get_data', None)55- if getter is not None:56- return getter(cache=cache)57+ return self.get_data(cache=cache)57- return self.data58 59 def get_json(self, force=False, silent=False, cache=True):60- """Parses the JSON request/response data and returns it. By default61- this function will return ``None`` if the mimetype is not62- :mimetype:`application/json` but this can be overridden by the63- ``force`` parameter. If parsing fails the64- :meth:`on_json_loading_failed` method on the request object will be65- invoked.60+ """Parse and return the data as JSON. If the mimetype does not indicate61+ JSON (:mimetype:`application/json`, see :meth:`is_json`), this returns62+ ``None`` unless ``force`` is true. If parsing fails,63+ :meth:`on_json_loading_failed` is called and its return value is used64+ as the return value.65 67- :param force: if set to ``True`` the mimetype is ignored.68- :param silent: if set to ``True`` this method will fail silently69- and return ``None``.70- :param cache: if set to ``True`` the parsed JSON data is remembered71- on the object.66+ :param force: Ignore the mimetype and always try to parse JSON.67+ :param silent: Silence parsing errors and return ``None`` instead.68+ :param cache: Store the parsed JSON to return for subsequent calls.69 """73- try:74- return getattr(self, '_cached_json')75- except AttributeError:76- pass70+ if cache and self._cached_json is not Ellipsis:71+ return self._cached_json72 73 if not (force or self.is_json):74 return None75 81- # We accept MIME charset header against the specification as certain82- # clients have been using this in the past. For responses, we assume83- # that if the response charset was set explicitly then the data had84- # been encoded correctly as well.76+ # We accept MIME charset against the specification as certain clients77+ # have used this in the past. For responses, we assume that if the78+ # charset is set then the data has been encoded correctly as well.79 charset = self.mimetype_params.get('charset')80+81 try:87- data = self._get_data_for_json(cache)88- if charset is not None:89- rv = json.loads(data, encoding=charset)90- else:91- rv = json.loads(data)82+ data = self._get_data_for_json(cache=cache)83+ rv = json.loads(data, encoding=charset)84 except ValueError as e:85 if silent:86 rv = None87 else:88 rv = self.on_json_loading_failed(e)89+90 if cache:91 self._cached_json = rv92+93 return rv94 95 def on_json_loading_failed(self, e):102- """Called if decoding of the JSON data failed. The return value of103- this method is used by :meth:`get_json` when an error occurred. The104- default implementation just raises a :class:`BadRequest` exception.96+ """Called if :meth:`get_json` parsing fails and isn't silenced. If97+ this method returns a value, it is used as the return value for98+ :meth:`get_json`. The default implementation raises a99+ :class:`BadRequest` exception.100 101 .. versionchanged:: 0.10107- Removed buggy previous behavior of generating a random JSON108- response. If you want that behavior back you can trivially109- add it by subclassing.102+ Raise a :exc:`BadRequest` error instead of returning an error103+ message as JSON. If you want that behavior you can add it by104+ subclassing.105 106 .. versionadded:: 0.8107 """113- ctx = _app_ctx_stack.top114- if ctx is not None and ctx.app.debug:108+ if current_app is not None and current_app.debug:109 raise BadRequest('Failed to decode JSON object: {0}'.format(e))110+111 raise BadRequest()112 113 114 class Request(RequestBase, JSONMixin):32 unmodified lines147 148 @property149 def max_content_length(self):150 """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""156- ctx = _app_ctx_stack.top157- if ctx is not None:158- return ctx.app.config['MAX_CONTENT_LENGTH']151+ if current_app:152+ return current_app.config['MAX_CONTENT_LENGTH']153 154 @property155 def endpoint(self):156 """The endpoint that matched the request. This in combination with27 unmodified lines184 RequestBase._load_form_data(self)185 186 # In debug mode we're replacing the files multidict with an ad-hoc187 # subclass that raises a different error for key errors.194- ctx = _app_ctx_stack.top195- if ctx is not None and ctx.app.debug and \196- self.mimetype != 'multipart/form-data' and not self.files:188+ if (189+ current_app190+ and current_app.debug191+ and self.mimetype != 'multipart/form-data'192+ and not self.files193+ ):194 from .debughelpers import attach_enctype_error_multidict195 attach_enctype_error_multidict(self)196 197 4 unmodified lines202 :meth:`~flask.Flask.make_response` will take care of that for you.203 204 If you want to replace the response object used you can subclass this and205 set :attr:`~flask.Flask.response_class` to your subclass.206+207+ .. versionchanged:: 1.0208+ JSON support is added to the response, like the request. This is useful209+ when testing to get the test client response data as JSON.210 """211+212 default_mimetype = 'text/html'213+214+ def _get_data_for_json(self, cache):215+ return self.get_data()modified:tests/test_testing.py+1 added-1 removed
265 unmodified lines266 267 def test_json_request_and_response(app, client):268 @app.route('/echo', methods=['POST'])269 def echo():270- return jsonify(flask.request.json)270+ return jsonify(flask.request.get_json())271 272 with client:273 json_data = {'drink': {'gin': 1, 'tonic': True}, 'price': 10}274 rv = client.post('/echo', json=json_data)43 unmodified linesmodified:CHANGES+7 added-5 removed
68 unmodified lines69 storing other types in the session cookie. (`#2352`_)70 - Only open the session if the request has not been pushed onto the context71 stack yet. This allows ``stream_with_context`` generators to access the same72 session that the containing view uses. (`#2354`_)73+- Add ``json`` keyword argument for the test client request methods. This will74+ dump the given object as JSON and set the appropriate content type.75+ (`#2358`_)76+- Extract JSON handling to a mixin applied to both the request and response77+ classes used by Flask. This adds the ``is_json`` and ``get_json`` methods to78+ the response to make testing JSON response much easier. (`#2358`_)79 80 .. _#1489: https://github.com/pallets/flask/pull/148981 .. _#1621: https://github.com/pallets/flask/pull/162182 .. _#1898: https://github.com/pallets/flask/pull/189813 unmodified lines96 .. _#2326: https://github.com/pallets/flask/pull/232697 .. _#2348: https://github.com/pallets/flask/pull/234898 .. _#2352: https://github.com/pallets/flask/pull/235299 .. _#2354: https://github.com/pallets/flask/pull/2354100+.. _#2358: https://github.com/pallets/flask/pull/2358101 102 Version 0.12.2103 --------------104 27 unmodified lines132 - Mimetype guessing in ``send_file`` now fails loudly and doesn't fall back to133 ``application/octet-stream``. See pull request ``#1988``.134 - Make ``flask.safe_join`` able to join multiple paths like ``os.path.join``135 (pull request ``#1730``).129-- Added `json` keyword argument to :meth:`flask.testing.FlaskClient.open`130- (and related ``get``, ``post``, etc.), which makes it more convenient to131- send JSON requests from the test client.132-- Added ``is_json`` and ``get_json`` to :class:``flask.wrappers.Response``133- in order to make it easier to build assertions when testing JSON responses.136 - Revert a behavior change that made the dev server crash instead of returning137 a Internal Server Error (pull request ``#2006``).138 - Correctly invoke response handlers for both regular request dispatching as139 well as error handlers.582 unmodified lines