On JSON requests, the JSON response should have Content-Type: application/json and the body of the response should be a JSON object.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Jeffrey Finkelstein · committed by Jeffrey Finkelstein · parent 7ed3cba · Browse files · 3 files·+66 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+66 added−4 removed
- other:+66 added−4 removed
Provenance
- Commit
9711fd4- Tree
9d6921b- Author
Jeffrey Finkelstein <jeffrey.finkelstein@gmail.com>- Committer
Jeffrey Finkelstein <jeffrey.finkelstein@gmail.com>- Parent
7ed3cba
3 files changed+66 added−4 removed
modified:flask/testsuite/helpers.py+12 added
38 unmodified lines39 c = app.test_client()40 rv = c.post('/json', data='malformed', content_type='application/json')41 self.assert_equal(rv.status_code, 400)42 43+ def test_json_bad_requests_content_type(self):44+ app = flask.Flask(__name__)45+ @app.route('/json', methods=['POST'])46+ def return_json():47+ return unicode(flask.request.json)48+ c = app.test_client()49+ rv = c.post('/json', data='malformed', content_type='application/json')50+ self.assert_equal(rv.status_code, 400)51+ self.assert_equal(rv.mimetype, 'application/json')52+ self.assert_('description' in flask.json.loads(rv.data))53+ self.assert_('<p>' not in flask.json.loads(rv.data)['description'])54+55 def test_json_body_encoding(self):56 app = flask.Flask(__name__)57 app.testing = True58 @app.route('/')313 unmodified linesmodified:flask/wrappers.py+52 added-4 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 12 from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase13-from werkzeug.exceptions import BadRequest13+from werkzeug.exceptions import BadRequest, HTTPException14 from werkzeug.utils import cached_property15 16 from .debughelpers import attach_enctype_error_multidict17 from .helpers import json, _assert_have_json18 from .globals import _request_ctx_stack19 20 21+class JSONHTTPException(HTTPException):22+ """A base class for HTTP exceptions with ``Content-Type:23+ application/json``.24+25+ The ``description`` attribute of this class must set to a string (*not* an26+ HTML string) which describes the error.27+28+ """29+30+ def get_body(self, environ):31+ """Overrides :meth:`werkzeug.exceptions.HTTPException.get_body` to32+ return the description of this error in JSON format instead of HTML.33+34+ """35+ return json.dumps(dict(description=self.get_description(environ)))36+37+ def get_headers(self, environ):38+ """Returns a list of headers including ``Content-Type:39+ application/json``.40+41+ """42+ return [('Content-Type', 'application/json')]43+44+45+class JSONBadRequest(JSONHTTPException, BadRequest):46+ """Represents an HTTP ``400 Bad Request`` error whose body contains an47+ error message in JSON format instead of HTML format (as in the superclass).48+49+ """50+51+ #: The description of the error which occurred as a string.52+ description = (53+ 'The browser (or proxy) sent a request that this server could not '54+ 'understand.'55+ )56+57+58 class Request(RequestBase):59 """The request object used by default in Flask. Remembers the60 matched endpoint and view arguments.61 82 unmodified lines144 return self.on_json_loading_failed(e)145 146 def on_json_loading_failed(self, e):147 """Called if decoding of the JSON data failed. The return value of111- this method is used by :attr:`json` when an error ocurred. The112- default implementation raises a :class:`~werkzeug.exceptions.BadRequest`.148+ this method is used by :attr:`json` when an error ocurred. The default149+ implementation raises a :class:`JSONBadRequest`, which is a subclass of150+ :class:`~werkzeug.exceptions.BadRequest` which sets the151+ ``Content-Type`` to ``application/json`` and provides a JSON-formatted152+ error description::153 154+ {"description": "The browser (or proxy) sent a request that \155+ this server could not understand."}156+157+ .. versionchanged:: 0.9158+159+ Return a :class:`JSONBadRequest` instead of a160+ :class:`~werkzeug.exceptions.BadRequest` by default.161+162 .. versionadded:: 0.8163 """116- raise BadRequest()164+ raise JSONBadRequest()165 166 def _load_form_data(self):167 RequestBase._load_form_data(self)168 18 unmodified linesmodified:CHANGES+2 added
6 unmodified lines7 -----------8 9 Relase date to be decided, codename to be chosen.10 11+- The :func:`flask.Request.on_json_loading_failed` now returns a JSON formatted12+ response by default.13 - The :func:`flask.url_for` function now can generate anchors to the14 generated links.15 - The :func:`flask.url_for` function now can also explicitly generate16 URL rules specific to a given HTTP method.332 unmodified lines