diff --git a/src/flask/app.py b/src/flask/app.py index 5a8223e5..f9db3b00 100644 --- a/src/flask/app.py +++ b/src/flask/app.py @@ -1830,6 +1830,9 @@ class Flask(Scaffold): ``dict`` A dictionary that will be jsonify'd before being returned. + ``list`` + A list that will be jsonify'd before being returned. + ``generator`` or ``iterator`` A generator that returns ``str`` or ``bytes`` to be streamed as the response. @@ -1855,6 +1858,7 @@ class Flask(Scaffold): .. versionchanged:: 2.2 A generator will be converted to a streaming response. + A list will be converted to a JSON response. .. versionchanged:: 1.1 A dict will be converted to a JSON response. @@ -1907,7 +1911,7 @@ class Flask(Scaffold): headers=headers, # type: ignore[arg-type] ) status = headers = None - elif isinstance(rv, dict): + elif isinstance(rv, (dict, list)): rv = jsonify(rv) elif isinstance(rv, BaseResponse) or callable(rv): # evaluate a WSGI callable, or coerce a different response @@ -1920,14 +1924,14 @@ class Flask(Scaffold): raise TypeError( f"{e}\nThe view function did not return a valid" " response. The return type must be a string," - " dict, tuple, Response instance, or WSGI" + " dict, list, tuple, Response instance, or WSGI" f" callable, but it was a {type(rv).__name__}." ).with_traceback(sys.exc_info()[2]) from None else: raise TypeError( "The view function did not return a valid" " response. The return type must be a string," - " dict, tuple, Response instance, or WSGI" + " dict, list, tuple, Response instance, or WSGI" f" callable, but it was a {type(rv).__name__}." ) diff --git a/src/flask/typing.py b/src/flask/typing.py index 4fb96545..30c9398c 100644 --- a/src/flask/typing.py +++ b/src/flask/typing.py @@ -7,7 +7,7 @@ if t.TYPE_CHECKING: # pragma: no cover # The possible types that are directly convertible or are a Response object. ResponseValue = t.Union[ - "Response", str, bytes, t.Dict[str, t.Any], t.Iterator[str], t.Iterator[bytes] + "Response", str, bytes, list, t.Dict[str, t.Any], t.Iterator[str], t.Iterator[bytes] ] # the possible types for an individual HTTP header diff --git a/tests/test_basic.py b/tests/test_basic.py index 91ba042f..dca48e2d 100644 --- a/tests/test_basic.py +++ b/tests/test_basic.py @@ -1166,6 +1166,10 @@ def test_response_types(app, client): def from_dict(): return {"foo": "bar"}, 201 + @app.route("/list") + def from_list(): + return ["foo", "bar"], 201 + assert client.get("/text").data == "Hällo Wörld".encode() assert client.get("/bytes").data == "Hällo Wörld".encode() @@ -1205,6 +1209,10 @@ def test_response_types(app, client): assert rv.json == {"foo": "bar"} assert rv.status_code == 201 + rv = client.get("/list") + assert rv.json == ["foo", "bar"] + assert rv.status_code == 201 + def test_response_type_errors(): app = flask.Flask(__name__)