Allow dictionary return values as JSON

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",
         }
This commit is contained in:
pgjones 2019-03-03 17:34:29 +00:00 committed by David Lord
parent 2616d97f32
commit 7bf8366970
No known key found for this signature in database
GPG key ID: 7A1C87E3F5BC42A8
4 changed files with 37 additions and 16 deletions

View file

@ -679,23 +679,26 @@ See :ref:`error-handlers` for more details.
About Responses
---------------
The return value from a view function is automatically converted into a
response object for you. If the return value is a string it's converted
into a response object with the string as response body, a ``200 OK``
status code and a :mimetype:`text/html` mimetype.
The logic that Flask applies to converting return values into
response objects is as follows:
The return value from a view function is automatically converted into
a response object for you. If the return value is a string it's
converted into a response object with the string as response body, a
``200 OK`` status code and a :mimetype:`text/html` mimetype. If the
return value is a dict, ``jsonify`` is called to produce a response.
The logic that Flask applies to converting return values into response
objects is as follows:
1. If a response object of the correct type is returned it's directly
returned from the view.
2. If it's a string, a response object is created with that data and the
default parameters.
3. If a tuple is returned the items in the tuple can provide extra information.
Such tuples have to be in the form ``(response, status, headers)``,
``(response, headers)`` or ``(response, status)`` where at least one item
has to be in the tuple. The ``status`` value will override the status code
and ``headers`` can be a list or dictionary of additional header values.
4. If none of that works, Flask will assume the return value is a
2. If it's a string, a response object is created with that data and
the default parameters.
3. If it's a dict, a response object is created using ``jsonify``.
4. If a tuple is returned the items in the tuple can provide extra
information. Such tuples have to be in the form
``(response, status)``, ``(response, headers)``, or
``(response, status, headers)``. The ``status`` value will override
the status code and ``headers`` can be a list or dictionary of
additional header values.
5. If none of that works, Flask will assume the return value is a
valid WSGI application and convert that into a response object.
If you want to get hold of the resulting response object inside the view