Merge pull request #4672 from greyli/return-list
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Allow to return list as JSON
authored by David Lord · committed by GitHub · parents 1626aff, 60b845e · Browse files · 6 files·+62 added−26 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+62 added−26 removed
- tests:+19 added−1 removed
- other:+43 added−25 removed
Provenance
- Commit
559a845- Tree
1f9d620- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
1626aff- Parent 2
60b845e
6 files changed+62 added−26 removed
modified:docs/quickstart.rst+22 added-19 removed
679 unmodified lines680 The return value from a view function is automatically converted into681 a response object for you. If the return value is a string it's682 converted into a response object with the string as response body, a683 ``200 OK`` status code and a :mimetype:`text/html` mimetype. If the684-return value is a dict, :func:`jsonify` is called to produce a response.685-The logic that Flask applies to converting return values into response686-objects is as follows:684+return value is a dict or list, :func:`jsonify` is called to produce a685+response. The logic that Flask applies to converting return values into686+response objects is as follows:687 688 1. If a response object of the correct type is returned it's directly689 returned from the view.690 2. If it's a string, a response object is created with that data and691 the default parameters.692-3. If it's a dict, a response object is created using ``jsonify``.693-4. If a tuple is returned the items in the tuple can provide extra692+3. If it's an iterator or generator returning strings or bytes, it is693+ treated as a streaming response.694+4. If it's a dict or list, a response object is created using695+ :func:`~flask.json.jsonify`.696+5. If a tuple is returned the items in the tuple can provide extra697 information. Such tuples have to be in the form698 ``(response, status)``, ``(response, headers)``, or699 ``(response, status, headers)``. The ``status`` value will override700 the status code and ``headers`` can be a list or dictionary of701 additional header values.699-5. If none of that works, Flask will assume the return value is a702+6. If none of that works, Flask will assume the return value is a703 valid WSGI application and convert that into a response object.704 705 If you want to get hold of the resulting response object inside the view706 you can use the :func:`~flask.make_response` function.22 unmodified lines729 APIs with JSON730 ``````````````731 732 A common response format when writing an API is JSON. It's easy to get730-started writing such an API with Flask. If you return a ``dict`` from a731-view, it will be converted to a JSON response.733+started writing such an API with Flask. If you return a ``dict`` or734+``list`` from a view, it will be converted to a JSON response.735 736 .. code-block:: python737 738 @app.route("/me")4 unmodified lines743 "theme": user.theme,744 "image": url_for("user_image", filename=user.image),745 }746 744-Depending on your API design, you may want to create JSON responses for745-types other than ``dict``. In that case, use the746-:func:`~flask.json.jsonify` function, which will serialize any supported747-JSON data type. Or look into Flask community extensions that support748-more complex applications.749-750-.. code-block:: python751-752- from flask import jsonify753-747 @app.route("/users")748 def users_api():749 users = get_all_users()757- return jsonify([user.to_json() for user in users])750+ return [user.to_json() for user in users]751 752+This is a shortcut to passing the data to the753+:func:`~flask.json.jsonify` function, which will serialize any supported754+JSON data type. That means that all the data in the dict or list must be755+JSON serializable.756 757+For complex types such as database models, you'll want to use a758+serialization library to convert the data to valid JSON types first.759+There are many serialization libraries and Flask API extensions760+maintained by the community that support more complex applications.761+762+763 .. _sessions:764 765 Sessions766 --------136 unmodified linesmodified:src/flask/app.py+11 added-5 removed
1828 unmodified lines1829 1830 ``dict``1831 A dictionary that will be jsonify'd before being returned.1832 1833+ ``list``1834+ A list that will be jsonify'd before being returned.1835+1836 ``generator`` or ``iterator``1837 A generator that returns ``str`` or ``bytes`` to be1838 streamed as the response.1839 17 unmodified lines1857 used to create a response object.1858 1859 .. versionchanged:: 2.21860 A generator will be converted to a streaming response.1861+ A list will be converted to a JSON response.1862 1863 .. versionchanged:: 1.11864 A dict will be converted to a JSON response.1865 44 unmodified lines1910 status=status,1911 headers=headers, # type: ignore[arg-type]1912 )1913 status = headers = None1910- elif isinstance(rv, dict):1914+ elif isinstance(rv, (dict, list)):1915 rv = jsonify(rv)1916 elif isinstance(rv, BaseResponse) or callable(rv):1917 # evaluate a WSGI callable, or coerce a different response1918 # class to the correct type4 unmodified lines1923 except TypeError as e:1924 raise TypeError(1925 f"{e}\nThe view function did not return a valid"1926 " response. The return type must be a string,"1923- " dict, tuple, Response instance, or WSGI"1924- f" callable, but it was a {type(rv).__name__}."1927+ " dict, list, tuple with headers or status,"1928+ " Response instance, or WSGI callable, but it"1929+ f" was a {type(rv).__name__}."1930 ).with_traceback(sys.exc_info()[2]) from None1931 else:1932 raise TypeError(1933 "The view function did not return a valid"1934 " response. The return type must be a string,"1930- " dict, tuple, Response instance, or WSGI"1931- f" callable, but it was a {type(rv).__name__}."1935+ " dict, list, tuple with headers or status,"1936+ " Response instance, or WSGI callable, but it was a"1937+ f" {type(rv).__name__}."1938 )1939 1940 rv = t.cast(Response, rv)1941 # prefer the status if it was provided369 unmodified linesmodified:src/flask/typing.py+7 added-1 removed
5 unmodified lines6 from werkzeug.wrappers import Response # noqa: F4017 8 # The possible types that are directly convertible or are a Response object.9 ResponseValue = t.Union[10- "Response", str, bytes, t.Dict[str, t.Any], t.Iterator[str], t.Iterator[bytes]10+ "Response",11+ str,12+ bytes,13+ t.List[t.Any],14+ t.Dict[str, t.Any],15+ t.Iterator[str],16+ t.Iterator[bytes],17 ]18 19 # the possible types for an individual HTTP header20 # This should be a Union, but mypy doesn't pass unless it's a TypeVar.46 unmodified linesmodified:tests/typing/typing_route.py+11 added-1 removed
23 unmodified lines24 25 26 @app.route("/json")27 def hello_json() -> Response:28- return jsonify({"response": "Hello, World!"})28+ return jsonify("Hello, World!")29 30 31+@app.route("/json/dict")32+def hello_json_dict() -> t.Dict[str, t.Any]:33+ return {"response": "Hello, World!"}34+35+36+@app.route("/json/dict")37+def hello_json_list() -> t.List[t.Any]:38+ return [{"message": "Hello"}, {"message": "World"}]39+40+41 @app.route("/generator")42 def hello_generator() -> t.Generator[str, None, None]:43 def show() -> t.Generator[str, None, None]:44 for x in range(100):54 unmodified linesmodified:tests/test_basic.py+8 added
1164 unmodified lines1165 @app.route("/dict")1166 def from_dict():1167 return {"foo": "bar"}, 2011168 1169+ @app.route("/list")1170+ def from_list():1171+ return ["foo", "bar"], 2011172+1173 assert client.get("/text").data == "Hällo Wörld".encode()1174 assert client.get("/bytes").data == "Hällo Wörld".encode()1175 1176 rv = client.get("/full_tuple")31 unmodified lines1208 rv = client.get("/dict")1209 assert rv.json == {"foo": "bar"}1210 assert rv.status_code == 2011211 1212+ rv = client.get("/list")1213+ assert rv.json == ["foo", "bar"]1214+ assert rv.status_code == 2011215 1216+1217 def test_response_type_errors():1218 app = flask.Flask(__name__)1219 app.testing = True1220 761 unmodified linesmodified:CHANGES.rst+3 added
63 unmodified lines64 - ``stream_with_context`` preserves context separately from a65 ``with client`` block. It will be cleaned up when66 ``response.get_data()`` or ``response.close()`` is called.67 68+- Allow returning a list from a view function, to convert it to a69+ JSON response like a dict is. :issue:`4672`70 71+72 Version 2.1.373 -------------74 75 Unreleased1289 unmodified lines