Mixin for JSON decoding code shared between request/response
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Adam Byrtek · committed by Markus Unterwaditzer · parent ca547f0 · Browse files · 1 file·+81 added−137 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+81 added−137 removed
- other:+81 added−137 removed
Provenance
- Commit
c9ef500- Tree
cda2deb- Author
Adam Byrtek <adambyrtek@gmail.com>- Committer
Markus Unterwaditzer <markus@unterwaditzer.net>- Parent
ca547f0
1 file changed+81 added−137 removed
modified:flask/wrappers.py+81 added-137 removed
23 unmodified lines24 return getter(cache=cache)25 return req.data26 27 28-def _is_mimetype_json(mimetype):29- if mimetype == 'application/json':30- return True31- if mimetype.startswith('application/') and mimetype.endswith('+json'):32- return True33- return False28+class JSONMixin(object):29+ """Mixin for both request and response classes to provide JSON parsing30+ capabilities.31 32+ .. versionadded:: 0.1233+ """34 35+ @property36+ def is_json(self):37+ """Indicates if this request/response is JSON or not. By default it38+ is considered to include JSON data if the mimetype is39+ :mimetype:`application/json` or :mimetype:`application/*+json`.40+ """41+ mt = self.mimetype42+ if mt == 'application/json':43+ return True44+ if mt.startswith('application/') and mt.endswith('+json'):45+ return True46+ return False47+48+ @property49+ def json(self):50+ """If the mimetype is :mimetype:`application/json` this will contain the51+ parsed JSON data. Otherwise this will be ``None``.52+53+ The :meth:`get_json` method should be used instead.54+ """55+ from warnings import warn56+ warn(DeprecationWarning('json is deprecated. '57+ 'Use get_json() instead.'), stacklevel=2)58+ return self.get_json()59+60+ def get_json(self, force=False, silent=False, cache=True):61+ """Parses the incoming JSON request data and returns it. By default62+ this function will return ``None`` if the mimetype is not63+ :mimetype:`application/json` but this can be overridden by the64+ ``force`` parameter. If parsing fails the65+ :meth:`on_json_loading_failed` method on the request object will be66+ invoked.67+68+ :param force: if set to ``True`` the mimetype is ignored.69+ :param silent: if set to ``True`` this method will fail silently70+ and return ``None``.71+ :param cache: if set to ``True`` the parsed JSON data is remembered72+ on the request.73+ """74+ rv = getattr(self, '_cached_json', _missing)75+ if rv is not _missing:76+ return rv77+78+ if not (force or self.is_json):79+ return None80+81+ # We accept a request charset against the specification as certain82+ # clients have been using this in the past. For responses, we assume83+ # that if the response charset was set explicitly then the data had84+ # been encoded correctly as well.85+ charset = self.mimetype_params.get('charset')86+ try:87+ data = _get_data(self, cache)88+ if charset is not None:89+ rv = json.loads(data, encoding=charset)90+ else:91+ rv = json.loads(data)92+ except ValueError as e:93+ if silent:94+ rv = None95+ else:96+ rv = self.on_json_loading_failed(e)97+ if cache:98+ self._cached_json = rv99+ return rv100+101+ def on_json_loading_failed(self, e):102+ """Called if decoding of the JSON data failed. The return value of103+ this method is used by :meth:`get_json` when an error occurred. The104+ default implementation just raises a :class:`BadRequest` exception.105+ """106+ raise BadRequest()107+108+36-class Request(RequestBase):109+class Request(RequestBase, JSONMixin):110 """The request object used by default in Flask. Remembers the111 matched endpoint and view arguments.112 113 It is what ends up as :class:`~flask.request`. If you want to replace61 unmodified lines175 """The name of the current blueprint"""176 if self.url_rule and '.' in self.url_rule.endpoint:177 return self.url_rule.endpoint.rsplit('.', 1)[0]178 106- @property107- def json(self):108- """If the mimetype is :mimetype:`application/json` this will contain the109- parsed JSON data. Otherwise this will be ``None``.110-111- The :meth:`get_json` method should be used instead.112- """113- from warnings import warn114- warn(DeprecationWarning('json is deprecated. '115- 'Use get_json() instead.'), stacklevel=2)116- return self.get_json()117-118- @property119- def is_json(self):120- """Indicates if this request is JSON or not. By default a request121- is considered to include JSON data if the mimetype is122- :mimetype:`application/json` or :mimetype:`application/*+json`.123-124- .. versionadded:: 0.11125- """126- return _is_mimetype_json(self.mimetype)127-128- def get_json(self, force=False, silent=False, cache=True):129- """Parses the incoming JSON request data and returns it. By default130- this function will return ``None`` if the mimetype is not131- :mimetype:`application/json` but this can be overridden by the132- ``force`` parameter. If parsing fails the133- :meth:`on_json_loading_failed` method on the request object will be134- invoked.135-136- :param force: if set to ``True`` the mimetype is ignored.137- :param silent: if set to ``True`` this method will fail silently138- and return ``None``.139- :param cache: if set to ``True`` the parsed JSON data is remembered140- on the request.141- """142- rv = getattr(self, '_cached_json', _missing)143- if rv is not _missing:144- return rv145-146- if not (force or self.is_json):147- return None148-149- # We accept a request charset against the specification as150- # certain clients have been using this in the past. This151- # fits our general approach of being nice in what we accept152- # and strict in what we send out.153- request_charset = self.mimetype_params.get('charset')154- try:155- data = _get_data(self, cache)156- if request_charset is not None:157- rv = json.loads(data, encoding=request_charset)158- else:159- rv = json.loads(data)160- except ValueError as e:161- if silent:162- rv = None163- else:164- rv = self.on_json_loading_failed(e)165- if cache:166- self._cached_json = rv167- return rv168-179 def on_json_loading_failed(self, e):180 """Called if decoding of the JSON data failed. The return value of181 this method is used by :meth:`get_json` when an error occurred. The182 default implementation just raises a :class:`BadRequest` exception.21 unmodified lines204 from .debughelpers import attach_enctype_error_multidict205 attach_enctype_error_multidict(self)206 207 198-class Response(ResponseBase):208+class Response(ResponseBase, JSONMixin):209 """The response object that is used by default in Flask. Works like the210 response object from Werkzeug but is set to have an HTML mimetype by211 default. Quite often you don't have to create this object yourself because212 :meth:`~flask.Flask.make_response` will take care of that for you.1 unmodified line214 If you want to replace the response object used you can subclass this and215 set :attr:`~flask.Flask.response_class` to your subclass.216 """217 default_mimetype = 'text/html'208-209- @property210- def json(self):211- """If the mimetype is :mimetype:`application/json` this will contain the212- parsed JSON data. Otherwise this will be ``None``.213-214- The :meth:`get_json` method should be used instead.215-216- .. versionadded:: 1.0217- """218- from warnings import warn219- warn(DeprecationWarning('json is deprecated. '220- 'Use get_json() instead.'), stacklevel=2)221- return self.get_json()222-223- @property224- def is_json(self):225- """Indicates if this response is JSON or not. By default a response226- is considered to include JSON data if the mimetype is227- :mimetype:`application/json` or :mimetype:`application/*+json`.228-229- .. versionadded:: 1.0230- """231- return _is_mimetype_json(self.mimetype)232-233- def get_json(self, force=False, silent=False, cache=True):234- """Parses the incoming JSON request data and returns it. If235- parsing fails the :meth:`on_json_loading_failed` method on the236- request object will be invoked. By default this function will237- only load the json data if the mimetype is :mimetype:`application/json`238- but this can be overridden by the `force` parameter.239-240- :param force: if set to ``True`` the mimetype is ignored.241- :param silent: if set to ``True`` this method will fail silently242- and return ``None``.243- :param cache: if set to ``True`` the parsed JSON data is remembered244- on the request.245-246- .. versionadded:: 1.0247- """248- rv = getattr(self, '_cached_json', _missing)249- if rv is not _missing:250- return rv251-252- if not (force or self.is_json):253- return None254-255- # We accept a request charset against the specification as256- # certain clients have been using this in the past. This257- # fits our general approach of being nice in what we accept258- # and strict in what we send out.259- request_charset = self.mimetype_params.get('charset')260- try:261- data = _get_data(self, cache)262- if request_charset is not None:263- rv = json.loads(data, encoding=request_charset)264- else:265- rv = json.loads(data)266- except ValueError as e:267- if silent:268- rv = None269- else:270- rv = self.on_json_loading_failed(e)271- if cache:272- self._cached_json = rv273- return rv