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
Provenance
- Commit
63129e8- Tree
fdf01ce- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
3b678b7- Parent 2
e97253e
7 files changed+186 added−105 removed
modified:docs/api.rst+1 added-1 removed
83 unmodified lines84 Response Objects85 ----------------86 87 .. autoclass:: flask.Response88- :members: set_cookie, data, mimetype88+ :members: set_cookie, data, mimetype, is_json, get_json89 90 .. attribute:: headers91 92 A :class:`~werkzeug.datastructures.Headers` object representing the response headers.733 unmodified linesmodified:docs/testing.rst+31 added
373 unmodified lines374 375 Note that in this case you have to use the ``sess`` object instead of the376 :data:`flask.session` proxy. The object however itself will provide the377 same interface.378+379+380+Testing JSON APIs381+-----------------382+383+.. versionadded:: 1.0384+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 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+ return jsonify(token=generate_token(email, password))397+398+ 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'])404+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+13 added
12 unmodified lines13 import werkzeug14 from contextlib import contextmanager15 from werkzeug.test import Client, EnvironBuilder16 from flask import _request_ctx_stack17+from flask.json import dumps as json_dumps18 19 try:20 from werkzeug.urls import url_parse21 except ImportError:30 unmodified lines52 if url.query:53 sep = b'?' if isinstance(url.query, bytes) else '?'54 path += sep + url.query55 56+ if 'json' in kwargs: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():63+ kwargs['data'] = json_dumps(kwargs.pop('json'))64+65+ if 'content_type' not in kwargs:66+ kwargs['content_type'] = 'application/json'67+68 return EnvironBuilder(path, base_url, *args, **kwargs)69 70 71 class FlaskClient(Client):104 unmodified linesmodified:flask/wrappers.py+113 added-104 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 _request_ctx_stack16+from flask import json17+from flask.globals import current_app18 18-_missing = object()19 20+class JSONMixin(object):21+ """Common mixin for both request and response objects to provide JSON22+ parsing capabilities.23 21-def _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+ """26 27+ _cached_json = Ellipsis28 29+ @property30+ def is_json(self):31+ """Check if the mimetype indicates JSON data, either32+ :mimetype:`application/json` or :mimetype:`application/*+json`.33+34+ .. versionadded:: 0.1135+ """36+ mt = self.mimetype37+ return (38+ mt == 'application/json'39+ or (mt.startswith('application/')) 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+ .. 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()55+56+ def _get_data_for_json(self, cache):57+ return self.get_data(cache=cache)58+59+ 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.65+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+ """70+ 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+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: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):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.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.105+106+ .. 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))110+111+ raise BadRequest()112+113+28-class Request(RequestBase):114+class Request(RequestBase, JSONMixin):115 """The request object used by default in Flask. Remembers the116 matched endpoint and view arguments.117 118 It is what ends up as :class:`~flask.request`. If you want to replace28 unmodified lines147 148 @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']153 154 @property155 def endpoint(self):156 """The endpoint that matched the request. This in combination with22 unmodified lines179 """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]182 98- @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``.103-104- 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()110-111- @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`.116-117- .. 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 False125-126- 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.133-134- :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 rv144-145- if not (force or self.is_json):146- return None147-148- # 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 rv167-168- 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.172-173- .. 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.177-178- .. 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()184-183 def _load_form_data(self):184 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.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)196 197 197-class Response(ResponseBase):198+class 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.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+20 added
12 unmodified lines13 import flask14 import werkzeug15 16 from flask._compat import text_type17+from flask.json import jsonify18 19 20 def test_environ_defaults_from_config(app, client):21 app.config['SERVER_NAME'] = 'example.com:1234'241 unmodified lines263 assert 'gin' in flask.request.form264 assert 'vodka' in flask.request.args265 266 267+def test_json_request_and_response(app, client):268+ @app.route('/echo', methods=['POST'])269+ def echo():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)275+276+ # Request should be in JSON277+ assert flask.request.is_json278+ assert flask.request.get_json() == json_data279+280+ # Response should be in JSON281+ assert rv.status_code == 200282+ assert rv.is_json283+ assert rv.get_json() == json_data284+285+286 def test_subdomain(app, client):287 app.config['SERVER_NAME'] = 'example.com'288 289 @app.route('/', subdomain='<company_id>')28 unmodified linesmodified:AUTHORS+1 added
7 unmodified lines8 9 Patches and Suggestions10 ```````````````````````11 12+- Adam Byrtek13 - Adam Zapletal14 - Ali Afshar15 - Chris Edgemon16 - Chris Grindstaff23 unmodified linesmodified:CHANGES+7 added
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 617 unmodified lines