Merge pull request #3111 from pgjones/master
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Allow dictionaries return values as JSON
authored by David Lord · committed by GitHub · parents 2616d97, 1ecc341 · Browse files · 4 files·+70 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+70 added−16 removed
- tests:+10 added−2 removed
- other:+60 added−14 removed
Provenance
- Commit
855d59b- Tree
365fa17- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
2616d97- Parent 2
1ecc341
4 files changed+70 added−16 removed
modified:docs/quickstart.rst+50 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, :func:`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.13 unmodified lines719 resp = make_response(render_template('error.html'), 404)720 resp.headers['X-Something'] = 'A value'721 return resp722 723+724+APIs with JSON725+``````````````726+727+A common response format when writing an API is JSON. It's easy to get728+started writing such an API with Flask. If you return a ``dict`` from a729+view, it will be converted to a JSON response.730+731+.. code-block:: python732+733+ @app.route("/me")734+ def me_api():735+ user = get_current_user()736+ return {737+ "username": user.username,738+ "theme": user.theme,739+ "image": url_for("user_image", filename=user.image),740+ }741+742+Depending on your API design, you may want to create JSON responses for743+types other than ``dict``. In that case, use the744+:func:`~flask.json.jsonify` function, which will serialize any supported745+JSON data type. Or look into Flask community extensions that support746+more complex applications.747+748+.. code-block:: python749+750+ @app.route("/users")751+ def users_api():752+ users = get_all_users()753+ return jsonify([user.to_json() for user in users])754+755+756 .. _sessions:757 758 Sessions759 --------135 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