Skip to content
Myr

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

5 files+48 added−2 removed

modified:src/flask/app.py+12 added-1 removed
3 unmodified lines
4import os5import sys6import typing as t7import weakref8from collections.abc import Iterator as _abc_Iterator9from datetime import timedelta10from itertools import chain11from threading import Lock12from types import TracebackType
1830 unmodified lines
18431844 ``dict``1845 A dictionary that will be jsonify'd before being returned.18461847 ``generator`` or ``iterator``1848 A generator that returns ``str`` or ``bytes`` to be1849 streamed as the response.18501851 ``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, and
11 unmodified lines
1866 :func:`callable`1867 The function is called as a WSGI application. The result is1868 used to create a response object.18691870 .. versionchanged:: 2.21871 A generator will be converted to a streaming response.18721873 .. versionchanged:: 1.11874 A dict will be converted to a JSON response.18751876 .. versionchanged:: 0.91877 Previously a tuple was interpreted as the arguments for the1878 response object.1879 """
30 unmodified lines
1910 )19111912 # 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 lines
modified:src/flask/typing.py+3 added-1 removed
4 unmodified lines
5 from werkzeug.datastructures import Headers # noqa: F4016 from werkzeug.wrappers import Response # noqa: F40178# The possible types that are directly convertible or are a Response object.9ResponseValue = t.Union["Response", str, bytes, t.Dict[str, t.Any]]9ResponseValue = t.Union[10 "Response", str, bytes, t.Dict[str, t.Any], t.Iterator[str], t.Iterator[bytes]11]1213# the possible types for an individual HTTP header14# This should be a Union, but mypy doesn't pass unless it's a TypeVar.15HeaderValue = t.Union[str, t.List[str], t.Tuple[str, ...]]
45 unmodified lines
modified:tests/typing/typing_route.py+26 added
1from __future__ import annotations23import typing as t4from http import HTTPStatus56from flask import Flask7from flask import jsonify8from flask import stream_template9from flask.templating import render_template10from flask.views import View11from flask.wrappers import Response12
14 unmodified lines
27def hello_json() -> Response:28 return jsonify({"response": "Hello, World!"})293031@app.route("/generator")32def 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"3637 return show()383940@app.route("/generator-expression")41def hello_generator_expression() -> t.Iterator[bytes]:42 return (f"data:{x}\n\n".encode() for x in range(100))434445@app.route("/iterator")46def hello_iterator() -> t.Iterator[str]:47 return iter([f"data:{x}\n\n" for x in range(100)])484950@app.route("/status")51@app.route("/status/<int:code>")52def tuple_status(code: int = 200) -> tuple[str, int]:53 return "hello", code
14 unmodified lines
68def return_template(name: str | None = None) -> str:69 return render_template("index.html", name=name)707172@app.route("/template")73def return_template_stream() -> t.Iterator[str]:74 return stream_template("index.html", name="Hello")757677class RenderTemplateView(View):78 def __init__(self: RenderTemplateView, template_name: str) -> None:79 self.template_name = template_name80
8 unmodified lines
modified:tests/test_basic.py+5 added
1274 unmodified lines
1275 assert rv.status_code == 4041276 assert rv.data == b"W00t"1277 assert rv.mimetype == "text/html"12781279 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"128312841285def 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 lines
modified:CHANGES.rst+2 added
36 unmodified lines
37 ``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`434445Version 2.1.346-------------
1291 unmodified lines