Allow dictionary return values as JSON
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This supports an increasingly common usecase whereby JSON is the primary response (rather than a templated string). Given Flask has a short syntax for HTML reponses, it seems fitting that it should also do so for JSON responses. In practice it allows, @app.route("/") def index(): return { "api_stuff": "values", }
authored by pgjones · committed by David Lord · parent 2616d97 · Browse files · 4 files·+37 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
4 files+37 added−16 removed
- tests:+10 added−2 removed
- other:+27 added−14 removed
Provenance
- Commit
7bf8366- Tree
fdb8cf1- Author
pgjones <philip.graham.jones@googlemail.com>- Committer
David Lord <davidism@gmail.com>- Parent
2616d97
4 files changed+37 added−16 removed
modified:docs/quickstart.rst+17 added-14 removed
677 unmodified lines678 679 About Responses680 ---------------681 682-The return value from a view function is automatically converted into a683-response object for you. If the return value is a string it's converted684-into a response object with the string as response body, a ``200 OK``685-status code and a :mimetype:`text/html` mimetype.686-The logic that Flask applies to converting return values into687-response objects is as follows:682+The return value from a view function is automatically converted into683+a response object for you. If the return value is a string it's684+converted into a response object with the string as response body, a685+``200 OK`` status code and a :mimetype:`text/html` mimetype. If the686+return value is a dict, ``jsonify`` is called to produce a response.687+The logic that Flask applies to converting return values into response688+objects is as follows:689 690 1. If a response object of the correct type is returned it's directly691 returned from the view.691-2. If it's a string, a response object is created with that data and the692- default parameters.693-3. If a tuple is returned the items in the tuple can provide extra information.694- Such tuples have to be in the form ``(response, status, headers)``,695- ``(response, headers)`` or ``(response, status)`` where at least one item696- has to be in the tuple. The ``status`` value will override the status code697- and ``headers`` can be a list or dictionary of additional header values.698-4. If none of that works, Flask will assume the return value is a692+2. If it's a string, a response object is created with that data and693+ the default parameters.694+3. If it's a dict, a response object is created using ``jsonify``.695+4. If a tuple is returned the items in the tuple can provide extra696+ information. Such tuples have to be in the form697+ ``(response, status)``, ``(response, headers)``, or698+ ``(response, status, headers)``. The ``status`` value will override699+ the status code and ``headers`` can be a list or dictionary of700+ additional header values.701+5. If none of that works, Flask will assume the return value is a702 valid WSGI application and convert that into a response object.703 704 If you want to get hold of the resulting response object inside the view705 you can use the :func:`~flask.make_response` function.156 unmodified linesmodified:flask/app.py+6 added
42 unmodified lines43 locked_cached_property,44 url_for,45 get_load_dotenv,46 )47+from .json import jsonify48 from .logging import create_logger49 from .sessions import SecureCookieSessionInterface50 from .signals import (51 appcontext_tearing_down,1949 unmodified lines2001 2002 ``bytes`` (``str`` in Python 2)2003 A response object is created with the bytes as the body.2004 2005+ ``dict``2006+ A dictionary that will be jsonify'd before being returned.2007+2008 ``tuple``2009 Either ``(body, status, headers)``, ``(body, status)``, or2010 ``(body, headers)``, where ``body`` is any of the other types2011 allowed here, ``status`` is a string or an integer, and55 unmodified lines2067 # waiting to do it manually, so that the class can handle any2068 # special logic2069 rv = self.response_class(rv, status=status, headers=headers)2070 status = headers = None2071+ elif isinstance(rv, dict):2072+ rv = jsonify(rv)2073 else:2074 # evaluate a WSGI callable, or coerce a different response2075 # class to the correct type2076 try:344 unmodified linesmodified:tests/test_basic.py+10 added-2 removed
1145 unmodified lines1146 @app.route("/wsgi")1147 def from_wsgi():1148 return NotFound()1149 1150- assert client.get("/text").data == u"Hällo Wörld".encode("utf-8")1151- assert client.get("/bytes").data == u"Hällo Wörld".encode("utf-8")1150+ @app.route('/dict')1151+ def from_dict():1152+ return {"foo": "bar"}, 2011153 1154+ assert client.get('/text').data == u'Hällo Wörld'.encode('utf-8')1155+ assert client.get('/bytes').data == u'Hällo Wörld'.encode('utf-8')1156+1157 rv = client.get("/full_tuple")1158 assert rv.data == b"Meh"1159 assert rv.headers["X-Foo"] == "Testing"1160 assert rv.status_code == 40023 unmodified lines1184 rv = client.get("/wsgi")1185 assert b"Not Found" in rv.data1186 assert rv.status_code == 4041187 1188+ rv = client.get('/dict')1189+ assert rv.json == {"foo": "bar"}1190+ assert rv.status_code == 2011191 1192+1193 def test_response_type_errors():1194 app = flask.Flask(__name__)1195 app.testing = True1196 779 unmodified linesmodified:CHANGES.rst+4 added
50 unmodified lines51 the Blinker library is not installed. :pr:`3208`52 - Add an ``--extra-files`` option to the ``flask run`` CLI command to53 specify extra files that will trigger the reloader on change.54 :issue:`2897`55+- Allow returning a dictionary from a view function. Similar to how56+ returning a string will produce a ``text/html`` response, returning57+ a dict will call ``jsonify`` to produce a ``application/json``58+ response. :pr:`3111`59 60 .. _#2935: https://github.com/pallets/flask/issues/293561 .. _#2957: https://github.com/pallets/flask/issues/295762 .. _#2994: https://github.com/pallets/flask/pull/2994947 unmodified lines