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

@ -44,6 +44,7 @@ from .helpers import (
url_for,
get_load_dotenv,
)
from .json import jsonify
from .logging import create_logger
from .sessions import SecureCookieSessionInterface
from .signals import (
@ -2001,6 +2002,9 @@ class Flask(_PackageBoundObject):
``bytes`` (``str`` in Python 2)
A response object is created with the bytes as the body.
``dict``
A dictionary that will be jsonify'd before being returned.
``tuple``
Either ``(body, status, headers)``, ``(body, status)``, or
``(body, headers)``, where ``body`` is any of the other types
@ -2064,6 +2068,8 @@ class Flask(_PackageBoundObject):
# special logic
rv = self.response_class(rv, status=status, headers=headers)
status = headers = None
elif isinstance(rv, dict):
rv = jsonify(rv)
else:
# evaluate a WSGI callable, or coerce a different response
# class to the correct type