Skip to content
Myr

Added request.get_json().

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

authored by Armin Ronacher · committed by Armin Ronacher · parent 335cbe0 · Browse files · 3 files+64 added−16 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+64 added−16 removed

  • other:+64 added−16 removed

3 files+64 added−16 removed

modified:flask/testsuite/helpers.py+5 added-4 removed
31 unmodified lines
32 def test_json_bad_requests(self):33 app = flask.Flask(__name__)34 @app.route('/json', methods=['POST'])35 def return_json():36 return flask.jsonify(foo=text_type(flask.request.json))36 return flask.jsonify(foo=text_type(flask.request.get_json()))37 c = app.test_client()38 rv = c.post('/json', data='malformed', content_type='application/json')39 self.assert_equal(rv.status_code, 400)40
1 unmodified line
42 app = flask.Flask(__name__)43 app.testing = True44 @app.route('/')45 def index():46 return flask.request.json46 return flask.request.get_json()4748 c = app.test_client()49 resp = c.get('/', data=u'"Hällo Wörld"'.encode('iso-8859-15'),50 content_type='application/json; charset=iso-8859-15')
30 unmodified lines
81 def test_json_attr(self):82 app = flask.Flask(__name__)83 @app.route('/add', methods=['POST'])84 def add():85 return text_type(flask.request.json['a'] + flask.request.json['b'])85 json = flask.request.get_json()86 return text_type(json['a'] + json['b'])87 c = app.test_client()88 rv = c.post('/add', data=flask.json.dumps({'a': 1, 'b': 2}),89 content_type='application/json')90 self.assert_equal(rv.data, b'3')
36 unmodified lines
127 app.json_encoder = MyEncoder128 app.json_decoder = MyDecoder129 @app.route('/', methods=['POST'])130 def index():130 return flask.json.dumps(flask.request.json['x'])131 return flask.json.dumps(flask.request.get_json()['x'])132 c = app.test_client()133 rv = c.post('/', data=flask.json.dumps({134 'x': {'_foo': 42}135 }), content_type='application/json')
452 unmodified lines
modified:flask/wrappers.py+57 added-12 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""1112from werkzeug.wrappers import Request as RequestBase, Response as ResponseBase13from werkzeug.utils import cached_property13from werkzeug.exceptions import BadRequest1415from .debughelpers import attach_enctype_error_multidict16from . import json17from .globals import _request_ctx_stack181920_missing = object()212223def _get_data(req, cache):24 getter = getattr(req, 'get_data', None)25 if getter is not None:26 return getter(cache=cache)27 return req.data282930class Request(RequestBase):31 """The request object used by default in Flask. Remembers the32 matched endpoint and view arguments.33
62 unmodified lines
96 """The name of the current blueprint"""97 if self.url_rule and '.' in self.url_rule.endpoint:98 return self.url_rule.endpoint.rsplit('.', 1)[0]9991 @cached_property100 @property101 def json(self):102 """If the mimetype is `application/json` this will contain the103 parsed JSON data. Otherwise this will be `None`.104105 The :meth:`get_json` method should be used instead.106 """96 if self.mimetype == 'application/json':97 request_charset = self.mimetype_params.get('charset')98 try:99 if request_charset is not None:100 return json.loads(self.data, encoding=request_charset)101 return json.loads(self.data)102 except ValueError as e:103 return self.on_json_loading_failed(e)107 # XXX: deprecate property108 return self.get_json()109110 def get_json(self, force=False, silent=False, cache=True):111 """Parses the incoming JSON request data and returns it. If112 parsing fails the :meth:`on_json_loading_failed` method on the113 request object will be invoked. By default this function will114 only load the json data if the mimetype is ``application/json``115 but this can be overriden by the `force` parameter.116117 :param force: if set to `True` the mimetype is ignored.118 :param silent: if set to `False` this method will fail silently119 and return `False`.120 :param cache: if set to `True` the parsed JSON data is remembered121 on the request.122 """123 rv = getattr(self, '_cached_json', _missing)124 if rv is not _missing:125 return rv126127 if self.mimetype != 'application/json' and not force:128 return None129130 # We accept a request charset against the specification as131 # certain clients have been using this in the past. This132 # fits our general approach of being nice in what we accept133 # and strict in what we send out.134 request_charset = self.mimetype_params.get('charset')135 try:136 data = _get_data(self, cache)137 if request_charset is not None:138 rv = json.loads(data, encoding=request_charset)139 else:140 rv = json.loads(data)141 except ValueError as e:142 if silent:143 rv = None144 else:145 rv = self.on_json_loading_failed(e)146 if cache:147 self._cached_json = rv148 return rv149150 def on_json_loading_failed(self, e):151 """Called if decoding of the JSON data failed. The return value of107 this method is used by :attr:`json` when an error occurred. The default108 implementation just raises a :class:`BadRequest` exception.152 this method is used by :meth:`get_json` when an error occurred. The153 default implementation just raises a :class:`BadRequest` exception.154155 .. versionchanged:: 0.10156 Removed buggy previous behavior of generating a random JSON157 response. If you want that behavior back you can trivially
27 unmodified lines
modified:CHANGES+2 added
75 unmodified lines
76 different hash seeds between different workers.77- Added `appcontext_pushed` and `appcontext_popped` signals.78- The builtin run method now takes the ``SERVER_NAME`` into account when79 picking the default port to run on.80- Added `flask.request.get_json()` as a replacement for the old81 `flask.request.json` property.8283Version 0.984-----------85
365 unmodified lines