Skip to content
Myr

Merge pull request #2358 from davidism/json-mixin

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

JSON support for test client and Response

authored by David Lord · committed by GitHub · parents 3b678b7, e97253e · Browse files · 7 files+186 added−105 removed
This commit

State

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

Diff stats

7 files+186 added−105 removed

  • tests:+20 added−0 removed
  • other:+166 added−105 removed

7 files+186 added−105 removed

modified:docs/api.rst+1 added-1 removed
83 unmodified lines
84Response Objects85----------------8687.. autoclass:: flask.Response88 :members: set_cookie, data, mimetype88 :members: set_cookie, data, mimetype, is_json, get_json8990 .. attribute:: headers9192 A :class:`~werkzeug.datastructures.Headers` object representing the response headers.
733 unmodified lines
modified:docs/testing.rst+31 added
373 unmodified lines
374375Note that in this case you have to use the ``sess`` object instead of the376:data:`flask.session` proxy. The object however itself will provide the377same interface.378379380Testing JSON APIs381-----------------382383.. versionadded:: 1.0384385Flask has great support for JSON, and is a popular choice for building JSON386APIs. Making requests with JSON data and examining JSON data in responses is387very convenient::388389 from flask import request, jsonify390391 @app.route('/api/auth')392 def auth():393 json_data = request.get_json()394 email = json_data['email']395 password = json_data['password']396 return jsonify(token=generate_token(email, password))397398 with app.test_client() as c: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'])404405Passing the ``json`` argument in the test client methods sets the request data406to the JSON-serialized object and sets the content type to407``application/json``. You can get the JSON data from the request or response408with ``get_json``.
modified:flask/testing.py+13 added
12 unmodified lines
13import werkzeug14from contextlib import contextmanager15from werkzeug.test import Client, EnvironBuilder16from flask import _request_ctx_stack17from flask.json import dumps as json_dumps1819try:20 from werkzeug.urls import url_parse21except ImportError:
30 unmodified lines
52 if url.query:53 sep = b'?' if isinstance(url.query, bytes) else '?'54 path += sep + url.query5556 if 'json' in kwargs:57 assert 'data' not in kwargs, (58 "Client cannot provide both 'json' and 'data'."59 )6061 # push a context so flask.json can use app's json attributes62 with app.app_context():63 kwargs['data'] = json_dumps(kwargs.pop('json'))6465 if 'content_type' not in kwargs:66 kwargs['content_type'] = 'application/json'6768 return EnvironBuilder(path, base_url, *args, **kwargs)697071class FlaskClient(Client):
104 unmodified lines
modified:flask/wrappers.py+113 added-104 removed
6 unmodified lines
78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from warnings import warn1212from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase13from werkzeug.exceptions import BadRequest14from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase1515from . import json16from .globals import _request_ctx_stack16from flask import json17from flask.globals import current_app1818_missing = object()1920class JSONMixin(object):21 """Common mixin for both request and response objects to provide JSON22 parsing capabilities.2321def _get_data(req, cache):22 getter = getattr(req, 'get_data', None)23 if getter is not None:24 return getter(cache=cache)25 return req.data24 .. versionadded:: 1.025 """2627 _cached_json = Ellipsis2829 @property30 def is_json(self):31 """Check if the mimetype indicates JSON data, either32 :mimetype:`application/json` or :mimetype:`application/*+json`.3334 .. versionadded:: 0.1135 """36 mt = self.mimetype37 return (38 mt == 'application/json'39 or (mt.startswith('application/')) 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``.4748 .. deprecated:: 1.049 Use :meth:`get_json` instead.50 """51 warn(DeprecationWarning(52 "'json' is deprecated. Use 'get_json()' instead."53 ), stacklevel=2)54 return self.get_json()5556 def _get_data_for_json(self, cache):57 return self.get_data(cache=cache)5859 def get_json(self, force=False, silent=False, cache=True):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.6566 :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 """70 if cache and self._cached_json is not Ellipsis:71 return self._cached_json7273 if not (force or self.is_json):74 return None7576 # 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')8081 try: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)8990 if cache:91 self._cached_json = rv9293 return rv9495 def on_json_loading_failed(self, e):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.100101 .. versionchanged:: 0.10102 Raise a :exc:`BadRequest` error instead of returning an error103 message as JSON. If you want that behavior you can add it by104 subclassing.105106 .. versionadded:: 0.8107 """108 if current_app is not None and current_app.debug:109 raise BadRequest('Failed to decode JSON object: {0}'.format(e))110111 raise BadRequest()11211328class Request(RequestBase):114class Request(RequestBase, JSONMixin):115 """The request object used by default in Flask. Remembers the116 matched endpoint and view arguments.117118 It is what ends up as :class:`~flask.request`. If you want to replace
28 unmodified lines
147148 @property149 def max_content_length(self):150 """Read-only view of the ``MAX_CONTENT_LENGTH`` config key."""65 ctx = _request_ctx_stack.top66 if ctx is not None:67 return ctx.app.config['MAX_CONTENT_LENGTH']151 if current_app:152 return current_app.config['MAX_CONTENT_LENGTH']153154 @property155 def endpoint(self):156 """The endpoint that matched the request. This in combination with
22 unmodified lines
179 """The name of the current blueprint"""180 if self.url_rule and '.' in self.url_rule.endpoint:181 return self.url_rule.endpoint.rsplit('.', 1)[0]18298 @property99 def json(self):100 """If the request has a JSON mimetype like :mimetype:`application/json`101 (see :meth:`is_json`), this will contain the parsed JSON data.102 Otherwise this will be ``None``.103104 The :meth:`get_json` method should be used instead.105 """106 from warnings import warn107 warn(DeprecationWarning('json is deprecated. '108 'Use get_json() instead.'), stacklevel=2)109 return self.get_json()110111 @property112 def is_json(self):113 """Indicates if this request is JSON or not. By default a request114 is considered to include JSON data if the mimetype is115 :mimetype:`application/json` or :mimetype:`application/*+json`.116117 .. versionadded:: 0.11118 """119 mt = self.mimetype120 if mt == 'application/json':121 return True122 if mt.startswith('application/') and mt.endswith('+json'):123 return True124 return False125126 def get_json(self, force=False, silent=False, cache=True):127 """Parses the incoming JSON request data and returns it. By default128 this function will return ``None`` if the request does not use a JSON129 mimetype like :mimetype:`application/json`. See :meth:`is_json`. This130 can be overridden by the ``force`` parameter. If parsing fails,131 the :meth:`on_json_loading_failed` method on the request object will be132 invoked.133134 :param force: if set to ``True`` the mimetype is ignored.135 :param silent: if set to ``True`` this method will fail silently136 and return ``None``.137 :param cache: if set to ``True`` the parsed JSON data is remembered138 on the request.139 """140 rv = getattr(self, '_cached_json', _missing)141 # We return cached JSON only when the cache is enabled.142 if cache and rv is not _missing:143 return rv144145 if not (force or self.is_json):146 return None147148 # We accept a request charset against the specification as149 # certain clients have been using this in the past. This150 # fits our general approach of being nice in what we accept151 # and strict in what we send out.152 request_charset = self.mimetype_params.get('charset')153 try:154 data = _get_data(self, cache)155 if request_charset is not None:156 rv = json.loads(data, encoding=request_charset)157 else:158 rv = json.loads(data)159 except ValueError as e:160 if silent:161 rv = None162 else:163 rv = self.on_json_loading_failed(e)164 if cache:165 self._cached_json = rv166 return rv167168 def on_json_loading_failed(self, e):169 """Called if decoding of the JSON data failed. The return value of170 this method is used by :meth:`get_json` when an error occurred. The171 default implementation just raises a :class:`BadRequest` exception.172173 .. versionchanged:: 0.10174 Removed buggy previous behavior of generating a random JSON175 response. If you want that behavior back you can trivially176 add it by subclassing.177178 .. versionadded:: 0.8179 """180 ctx = _request_ctx_stack.top181 if ctx is not None and ctx.app.config.get('DEBUG', False):182 raise BadRequest('Failed to decode JSON object: {0}'.format(e))183 raise BadRequest()184183 def _load_form_data(self):184 RequestBase._load_form_data(self)185186 # In debug mode we're replacing the files multidict with an ad-hoc187 # subclass that raises a different error for key errors.190 ctx = _request_ctx_stack.top191 if ctx is not None and ctx.app.debug and \192 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)196197197class Response(ResponseBase):198class Response(ResponseBase, JSONMixin):199 """The response object that is used by default in Flask. Works like the200 response object from Werkzeug but is set to have an HTML mimetype by201 default. Quite often you don't have to create this object yourself because202 :meth:`~flask.Flask.make_response` will take care of that for you.203204 If you want to replace the response object used you can subclass this and205 set :attr:`~flask.Flask.response_class` to your subclass.206207 .. 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 """211212 default_mimetype = 'text/html'213214 def _get_data_for_json(self, cache):215 return self.get_data()
modified:tests/test_testing.py+20 added
12 unmodified lines
13import flask14import werkzeug1516from flask._compat import text_type17from flask.json import jsonify181920def test_environ_defaults_from_config(app, client):21 app.config['SERVER_NAME'] = 'example.com:1234'
241 unmodified lines
263 assert 'gin' in flask.request.form264 assert 'vodka' in flask.request.args265266267def test_json_request_and_response(app, client):268 @app.route('/echo', methods=['POST'])269 def echo():270 return jsonify(flask.request.get_json())271272 with client:273 json_data = {'drink': {'gin': 1, 'tonic': True}, 'price': 10}274 rv = client.post('/echo', json=json_data)275276 # Request should be in JSON277 assert flask.request.is_json278 assert flask.request.get_json() == json_data279280 # Response should be in JSON281 assert rv.status_code == 200282 assert rv.is_json283 assert rv.get_json() == json_data284285286def test_subdomain(app, client):287 app.config['SERVER_NAME'] = 'example.com'288289 @app.route('/', subdomain='<company_id>')
28 unmodified lines
modified:AUTHORS+1 added
7 unmodified lines
89Patches and Suggestions10```````````````````````1112- Adam Byrtek13- Adam Zapletal14- Ali Afshar15- Chris Edgemon16- Chris Grindstaff
23 unmodified lines
modified:CHANGES+7 added
68 unmodified lines
69 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`_)7980.. _#1489: https://github.com/pallets/flask/pull/148981.. _#1621: https://github.com/pallets/flask/pull/162182.. _#1898: https://github.com/pallets/flask/pull/1898
13 unmodified lines
96.. _#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/2358101102Version 0.12.2103--------------104
617 unmodified lines