view functions can return generators as responses directly
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by pgjones · committed by David Lord · parent 7f2a0f4 · Browse files · 5 files·+48 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+48 added−2 removed
- tests:+31 added−0 removed
- other:+17 added−2 removed
Provenance
- Commit
762382e- Tree
4613910- Author
pgjones <philip.graham.jones@googlemail.com>- Committer
David Lord <davidism@gmail.com>- Parent
7f2a0f4
5 files changed+48 added−2 removed
modified:src/flask/app.py+12 added-1 removed
3 unmodified lines4 import os5 import sys6 import typing as t7 import weakref8+from collections.abc import Iterator as _abc_Iterator9 from datetime import timedelta10 from itertools import chain11 from threading import Lock12 from types import TracebackType1830 unmodified lines1843 1844 ``dict``1845 A dictionary that will be jsonify'd before being returned.1846 1847+ ``generator`` or ``iterator``1848+ A generator that returns ``str`` or ``bytes`` to be1849+ streamed as the response.1850+1851 ``tuple``1852 Either ``(body, status, headers)``, ``(body, status)``, or1853 ``(body, headers)``, where ``body`` is any of the other types1854 allowed here, ``status`` is a string or an integer, and11 unmodified lines1866 :func:`callable`1867 The function is called as a WSGI application. The result is1868 used to create a response object.1869 1870+ .. versionchanged:: 2.21871+ A generator will be converted to a streaming response.1872+1873+ .. versionchanged:: 1.11874+ A dict will be converted to a JSON response.1875+1876 .. versionchanged:: 0.91877 Previously a tuple was interpreted as the arguments for the1878 response object.1879 """30 unmodified lines1910 )1911 1912 # make sure the body is an instance of the response class1913 if not isinstance(rv, self.response_class):1903- if isinstance(rv, (str, bytes, bytearray)):1914+ if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, _abc_Iterator):1915 # let the response class set the status and headers instead of1916 # waiting to do it manually, so that the class can handle any1917 # special logic1918 rv = self.response_class(395 unmodified linesmodified:src/flask/typing.py+3 added-1 removed
4 unmodified lines5 from werkzeug.datastructures import Headers # noqa: F4016 from werkzeug.wrappers import Response # noqa: F4017 8 # The possible types that are directly convertible or are a Response object.9-ResponseValue = t.Union["Response", str, bytes, t.Dict[str, t.Any]]9+ResponseValue = t.Union[10+ "Response", str, bytes, t.Dict[str, t.Any], t.Iterator[str], t.Iterator[bytes]11+]12 13 # the possible types for an individual HTTP header14 # This should be a Union, but mypy doesn't pass unless it's a TypeVar.15 HeaderValue = t.Union[str, t.List[str], t.Tuple[str, ...]]45 unmodified linesmodified:tests/typing/typing_route.py+26 added
1 from __future__ import annotations2 3+import typing as t4 from http import HTTPStatus5 6 from flask import Flask7 from flask import jsonify8+from flask import stream_template9 from flask.templating import render_template10 from flask.views import View11 from flask.wrappers import Response12 14 unmodified lines27 def hello_json() -> Response:28 return jsonify({"response": "Hello, World!"})29 30 31+@app.route("/generator")32+def hello_generator() -> t.Generator[str, None, None]:33+ def show() -> t.Generator[str, None, None]:34+ for x in range(100):35+ yield f"data:{x}\n\n"36+37+ return show()38+39+40+@app.route("/generator-expression")41+def hello_generator_expression() -> t.Iterator[bytes]:42+ return (f"data:{x}\n\n".encode() for x in range(100))43+44+45+@app.route("/iterator")46+def hello_iterator() -> t.Iterator[str]:47+ return iter([f"data:{x}\n\n" for x in range(100)])48+49+50 @app.route("/status")51 @app.route("/status/<int:code>")52 def tuple_status(code: int = 200) -> tuple[str, int]:53 return "hello", code14 unmodified lines68 def return_template(name: str | None = None) -> str:69 return render_template("index.html", name=name)70 71 72+@app.route("/template")73+def return_template_stream() -> t.Iterator[str]:74+ return stream_template("index.html", name="Hello")75+76+77 class RenderTemplateView(View):78 def __init__(self: RenderTemplateView, template_name: str) -> None:79 self.template_name = template_name80 8 unmodified linesmodified:tests/test_basic.py+5 added
1274 unmodified lines1275 assert rv.status_code == 4041276 assert rv.data == b"W00t"1277 assert rv.mimetype == "text/html"1278 1279+ rv = flask.make_response(c for c in "Hello")1280+ assert rv.status_code == 2001281+ assert rv.data == b"Hello"1282+ assert rv.mimetype == "text/html"1283 1284+1285 def test_make_response_with_response_instance(app, req_ctx):1286 rv = flask.make_response(flask.jsonify({"msg": "W00t"}), 400)1287 assert rv.status_code == 4001288 assert rv.data == b'{"msg":"W00t"}\n'741 unmodified linesmodified:CHANGES.rst+2 added
36 unmodified lines37 ``app.cli`` or ``blueprint.cli`` with ``@with_appcontext``, an app38 context will already be active at that point. :issue:`2410`39 - ``SessionInterface.get_expiration_time`` uses a timezone-aware40 value. :pr:`4645`41+- View functions can return generators directly instead of wrapping42+ them in a ``Response``. :pr:`4629`43 44 45 Version 2.1.346 -------------1291 unmodified lines