From e5bba9deb5c9ab9c66bea5c17e96741777fe46ab Mon Sep 17 00:00:00 2001 From: Armin Ronacher Date: Sat, 8 Feb 2014 17:01:13 +0000 Subject: [PATCH] Added support for custom JSON mimetypes --- CHANGES | 1 + flask/testsuite/helpers.py | 9 +++++++++ flask/wrappers.py | 17 ++++++++++++++++- 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/CHANGES b/CHANGES index 99d00134..ed5ad9a2 100644 --- a/CHANGES +++ b/CHANGES @@ -14,6 +14,7 @@ Version 1.0 `False` it will only be modified if the session actually modifies. Non permanent sessions are not affected by this and will always expire if the browser window closes. +- Made Flask support custom JSON mimetypes for incoming data. Version 0.10.2 -------------- diff --git a/flask/testsuite/helpers.py b/flask/testsuite/helpers.py index f8edd4e0..f8460d3c 100644 --- a/flask/testsuite/helpers.py +++ b/flask/testsuite/helpers.py @@ -38,6 +38,15 @@ class JSONTestCase(FlaskTestCase): rv = c.post('/json', data='malformed', content_type='application/json') self.assert_equal(rv.status_code, 400) + def test_json_custom_mimetypes(self): + app = flask.Flask(__name__) + @app.route('/json', methods=['POST']) + def return_json(): + return flask.request.get_json() + c = app.test_client() + rv = c.post('/json', data='"foo"', content_type='application/x+json') + self.assert_equal(rv.data, b'foo') + def test_json_body_encoding(self): app = flask.Flask(__name__) app.testing = True diff --git a/flask/wrappers.py b/flask/wrappers.py index 038ba6fc..1d6fbef5 100644 --- a/flask/wrappers.py +++ b/flask/wrappers.py @@ -107,6 +107,21 @@ class Request(RequestBase): # XXX: deprecate property return self.get_json() + @property + def is_json(self): + """Indicates if this request is JSON or not. By default a request + is considered to include JSON data if the mimetype is + ``application/json`` or ``application/*+json``. + + .. versionadded:: 0.11 + """ + mt = self.mimetype + if mt == 'application/json': + return True + if mt.startswith('application/') and mt.endswith('+json'): + return True + return False + def get_json(self, force=False, silent=False, cache=True): """Parses the incoming JSON request data and returns it. If parsing fails the :meth:`on_json_loading_failed` method on the @@ -124,7 +139,7 @@ class Request(RequestBase): if rv is not _missing: return rv - if self.mimetype != 'application/json' and not force: + if not (force or self.is_json): return None # We accept a request charset against the specification as