Skip to content
Myr

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

6 files+62 added−26 removed

modified:docs/quickstart.rst+22 added-19 removed
679 unmodified lines
680The return value from a view function is automatically converted into681a response object for you. If the return value is a string it's682converted into a response object with the string as response body, a683``200 OK`` status code and a :mimetype:`text/html` mimetype. If the684return value is a dict, :func:`jsonify` is called to produce a response.685The logic that Flask applies to converting return values into response686objects is as follows:684return value is a dict or list, :func:`jsonify` is called to produce a685response. The logic that Flask applies to converting return values into686response objects is as follows:6876881. If a response object of the correct type is returned it's directly689 returned from the view.6902. If it's a string, a response object is created with that data and691 the default parameters.6923. If it's a dict, a response object is created using ``jsonify``.6934. If a tuple is returned the items in the tuple can provide extra6923. If it's an iterator or generator returning strings or bytes, it is693 treated as a streaming response.6944. If it's a dict or list, a response object is created using695 :func:`~flask.json.jsonify`.6965. 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.6995. If none of that works, Flask will assume the return value is a7026. If none of that works, Flask will assume the return value is a703 valid WSGI application and convert that into a response object.704705If you want to get hold of the resulting response object inside the view706you can use the :func:`~flask.make_response` function.
22 unmodified lines
729APIs with JSON730``````````````731732A common response format when writing an API is JSON. It's easy to get730started writing such an API with Flask. If you return a ``dict`` from a731view, it will be converted to a JSON response.733started writing such an API with Flask. If you return a ``dict`` or734``list`` from a view, it will be converted to a JSON response.735736.. code-block:: python737738 @app.route("/me")
4 unmodified lines
743 "theme": user.theme,744 "image": url_for("user_image", filename=user.image),745 }746744Depending on your API design, you may want to create JSON responses for745types other than ``dict``. In that case, use the746:func:`~flask.json.jsonify` function, which will serialize any supported747JSON data type. Or look into Flask community extensions that support748more complex applications.749750.. code-block:: python751752 from flask import jsonify753747 @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]751752This is a shortcut to passing the data to the753:func:`~flask.json.jsonify` function, which will serialize any supported754JSON data type. That means that all the data in the dict or list must be755JSON serializable.756757For complex types such as database models, you'll want to use a758serialization library to convert the data to valid JSON types first.759There are many serialization libraries and Flask API extensions760maintained by the community that support more complex applications.761762763.. _sessions:764765Sessions766--------
136 unmodified lines
modified:src/flask/app.py+11 added-5 removed
1828 unmodified lines
18291830 ``dict``1831 A dictionary that will be jsonify'd before being returned.18321833 ``list``1834 A list that will be jsonify'd before being returned.18351836 ``generator`` or ``iterator``1837 A generator that returns ``str`` or ``bytes`` to be1838 streamed as the response.1839
17 unmodified lines
1857 used to create a response object.18581859 .. versionchanged:: 2.21860 A generator will be converted to a streaming response.1861 A list will be converted to a JSON response.18621863 .. versionchanged:: 1.11864 A dict will be converted to a JSON response.1865
44 unmodified lines
1910 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 type
4 unmodified lines
1923 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 )19391940 rv = t.cast(Response, rv)1941 # prefer the status if it was provided
369 unmodified lines
modified:src/flask/typing.py+7 added-1 removed
5 unmodified lines
6 from werkzeug.wrappers import Response # noqa: F40178# The possible types that are directly convertible or are a Response object.9ResponseValue = 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]1819# 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 lines
modified:tests/typing/typing_route.py+11 added-1 removed
23 unmodified lines
242526@app.route("/json")27def hello_json() -> Response:28 return jsonify({"response": "Hello, World!"})28 return jsonify("Hello, World!")293031@app.route("/json/dict")32def hello_json_dict() -> t.Dict[str, t.Any]:33 return {"response": "Hello, World!"}343536@app.route("/json/dict")37def hello_json_list() -> t.List[t.Any]:38 return [{"message": "Hello"}, {"message": "World"}]394041@app.route("/generator")42def hello_generator() -> t.Generator[str, None, None]:43 def show() -> t.Generator[str, None, None]:44 for x in range(100):
54 unmodified lines
modified:tests/test_basic.py+8 added
1164 unmodified lines
1165 @app.route("/dict")1166 def from_dict():1167 return {"foo": "bar"}, 20111681169 @app.route("/list")1170 def from_list():1171 return ["foo", "bar"], 20111721173 assert client.get("/text").data == "Hällo Wörld".encode()1174 assert client.get("/bytes").data == "Hällo Wörld".encode()11751176 rv = client.get("/full_tuple")
31 unmodified lines
1208 rv = client.get("/dict")1209 assert rv.json == {"foo": "bar"}1210 assert rv.status_code == 20112111212 rv = client.get("/list")1213 assert rv.json == ["foo", "bar"]1214 assert rv.status_code == 201121512161217def test_response_type_errors():1218 app = flask.Flask(__name__)1219 app.testing = True1220
761 unmodified lines
modified:CHANGES.rst+3 added
63 unmodified lines
64 - ``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.6768- Allow returning a list from a view function, to convert it to a69 JSON response like a dict is. :issue:`4672`707172Version 2.1.373-------------7475Unreleased
1289 unmodified lines