Merge pull request #439 from aisipos/jsonexceptions
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add new exceptions module, to implement JSONHttpException and JSONBadRequest.
authored by Ron DuPlain · committed by Ron DuPlain · parents df772df, 71b3511 · Browse files · 4 files·+78 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
4 files+78 added−4 removed
- other:+78 added−4 removed
Provenance
- Commit
f430039- Tree
7266687- Author
Ron DuPlain <ron.duplain@gmail.com>- Committer
Ron DuPlain <ron.duplain@gmail.com>- Parent 1
df772df- Parent 2
71b3511
4 files changed+78 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('/')354 unmodified linesadded:flask/exceptions.py+49 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.exceptions4+ ~~~~~~~~~~~~5+6+ Flask specific additions to :class:`~werkzeug.exceptions.HTTPException`7+8+ :copyright: (c) 2011 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+from werkzeug.exceptions import HTTPException, BadRequest12+from .helpers import json13+14+15+class JSONHTTPException(HTTPException):16+ """A base class for HTTP exceptions with ``Content-Type:17+ application/json``.18+19+ The ``description`` attribute of this class must set to a string (*not* an20+ HTML string) which describes the error.21+22+ """23+24+ def get_body(self, environ):25+ """Overrides :meth:`werkzeug.exceptions.HTTPException.get_body` to26+ return the description of this error in JSON format instead of HTML.27+28+ """29+ return json.dumps(dict(description=self.get_description(environ)))30+31+ def get_headers(self, environ):32+ """Returns a list of headers including ``Content-Type:33+ application/json``.34+35+ """36+ return [('Content-Type', 'application/json')]37+38+39+class JSONBadRequest(JSONHTTPException, BadRequest):40+ """Represents an HTTP ``400 Bad Request`` error whose body contains an41+ error message in JSON format instead of HTML format (as in the superclass).42+43+ """44+45+ #: The description of the error which occurred as a string.46+ description = (47+ 'The browser (or proxy) sent a request that this server could not '48+ 'understand.'49+ )modified:flask/wrappers.py+15 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.utils import cached_property14 15+from .exceptions import JSONBadRequest16 from .debughelpers import attach_enctype_error_multidict17 from .helpers import json, _assert_have_json18 from .globals import _request_ctx_stack19 87 unmodified lines107 return self.on_json_loading_failed(e)108 109 def on_json_loading_failed(self, e):110 """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`.111+ this method is used by :attr:`json` when an error ocurred. The default112+ implementation raises a :class:`JSONBadRequest`, which is a subclass of113+ :class:`~werkzeug.exceptions.BadRequest` which sets the114+ ``Content-Type`` to ``application/json`` and provides a JSON-formatted115+ error description::116 117+ {"description": "The browser (or proxy) sent a request that \118+ this server could not understand."}119+120+ .. versionchanged:: 0.9121+122+ Return a :class:`JSONBadRequest` instead of a123+ :class:`~werkzeug.exceptions.BadRequest` by default.124+125 .. versionadded:: 0.8126 """116- raise BadRequest()127+ raise JSONBadRequest()128 129 def _load_form_data(self):130 RequestBase._load_form_data(self)131 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.344 unmodified lines