Merge pull request #4629 from pgjones/generate
Before adoption: this commit came in with the history the project adopted, so no landing records it.
allow view to return generator
authored by David Lord · committed by GitHub · parents 7f2a0f4, 46433e9 · Browse files · 11 files·+187 added−39 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+187 added−39 removed
- tests:+40 added−0 removed
- other:+147 added−39 removed
Provenance
- Commit
ab36542- Tree
6cc0ca3- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
7f2a0f4- Parent 2
46433e9
11 files changed+187 added−39 removed
modified:docs/patterns/streaming.rst+40 added-35 removed
18 unmodified lines19 def generate_large_csv():20 def generate():21 for row in iter_all_rows():22 yield f"{','.join(row)}\n"23- return app.response_class(generate(), mimetype='text/csv')23+ return generate(), {"Content-Type": "text/csv")24 25 Each ``yield`` expression is directly sent to the browser. Note though26 that some WSGI middlewares might break streaming, so be careful there in27 debug environments with profilers and other things you might have enabled.28 29 Streaming from Templates30 ------------------------31 32-The Jinja2 template engine also supports rendering templates piece by33-piece. This functionality is not directly exposed by Flask because it is34-quite uncommon, but you can easily do it yourself::32+The Jinja2 template engine supports rendering a template piece by33+piece, returning an iterator of strings. Flask provides the34+:func:`~flask.stream_template` and :func:`~flask.stream_template_string`35+functions to make this easier to use.36 36- def stream_template(template_name, **context):37- app.update_template_context(context)38- t = app.jinja_env.get_template(template_name)39- rv = t.stream(context)40- rv.enable_buffering(5)41- return rv37+.. code-block:: python38 43- @app.route('/my-large-page.html')44- def render_large_template():45- rows = iter_all_rows()46- return app.response_class(stream_template('the_template.html', rows=rows))39+ from flask import stream_template40 48-The trick here is to get the template object from the Jinja2 environment49-on the application and to call :meth:`~jinja2.Template.stream` instead of50-:meth:`~jinja2.Template.render` which returns a stream object instead of a51-string. Since we're bypassing the Flask template render functions and52-using the template object itself we have to make sure to update the render53-context ourselves by calling :meth:`~flask.Flask.update_template_context`.54-The template is then evaluated as the stream is iterated over. Since each55-time you do a yield the server will flush the content to the client you56-might want to buffer up a few items in the template which you can do with57-``rv.enable_buffering(size)``. ``5`` is a sane default.41+ @app.get("/timeline")42+ def timeline():43+ return stream_template("timeline.html")44 45+The parts yielded by the render stream tend to match statement blocks in46+the template.47+48+49 Streaming with Context50 ----------------------51 62-.. versionadded:: 0.952+The :data:`~flask.request` will not be active while the generator is53+running, because the view has already returned at that point. If you try54+to access ``request``, you'll get a ``RuntimeError``.55 64-Note that when you stream data, the request context is already gone the65-moment the function executes. Flask 0.9 provides you with a helper that66-can keep the request context around during the execution of the67-generator::56+If your generator function relies on data in ``request``, use the57+:func:`~flask.stream_with_context` wrapper. This will keep the request58+context active during the generator.59 60+.. code-block:: python61+62 from flask import stream_with_context, request63+ from markupsafe import escape64 65 @app.route('/stream')66 def streamed_response():67 def generate():74- yield 'Hello '75- yield request.args['name']76- yield '!'77- return app.response_class(stream_with_context(generate()))68+ yield '<p>Hello '69+ yield escape(request.args['name'])70+ yield '!</p>'71+ return stream_with_context(generate())72 79-Without the :func:`~flask.stream_with_context` function you would get a80-:class:`RuntimeError` at that point.73+It can also be used as a decorator.74+75+.. code-block:: python76+77+ @stream_with_context78+ def generate():79+ ...80+81+ return generate()82+83+The :func:`~flask.stream_template` and84+:func:`~flask.stream_template_string` functions automatically85+use :func:`~flask.stream_with_context` if a request is active.modified:docs/api.rst+4 added
285 unmodified lines286 .. autofunction:: render_template287 288 .. autofunction:: render_template_string289 290+.. autofunction:: stream_template291+292+.. autofunction:: stream_template_string293+294 .. autofunction:: get_template_attribute295 296 Configuration297 -------------480 unmodified linesmodified:docs/templating.rst+26 added
199 unmodified lines200 201 You could also build `format_price` as a template filter (see202 :ref:`registering-filters`), but this demonstrates how to pass functions in a203 context processor.204+205+Streaming206+---------207+208+It can be useful to not render the whole template as one complete209+string, instead render it as a stream, yielding smaller incremental210+strings. This can be used for streaming HTML in chunks to speed up211+initial page load, or to save memory when rendering a very large212+template.213+214+The Jinja2 template engine supports rendering a template piece215+by piece, returning an iterator of strings. Flask provides the216+:func:`~flask.stream_template` and :func:`~flask.stream_template_string`217+functions to make this easier to use.218+219+.. code-block:: python220+221+ from flask import stream_template222+223+ @app.get("/timeline")224+ def timeline():225+ return stream_template("timeline.html")226+227+These functions automatically apply the228+:func:`~flask.stream_with_context` wrapper if a request is active, so229+that it remains available in the template.modified:src/flask/__init__.py+2 added
39 unmodified lines40 from .signals import signals_available as signals_available41 from .signals import template_rendered as template_rendered42 from .templating import render_template as render_template43 from .templating import render_template_string as render_template_string44+from .templating import stream_template as stream_template45+from .templating import stream_template_string as stream_template_string46 47 __version__ = "2.2.0.dev0"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/templating.py+56 added-2 removed
5 unmodified lines6 from jinja2 import TemplateNotFound7 8 from .globals import _app_ctx_stack9 from .globals import _request_ctx_stack10+from .globals import current_app11+from .globals import request12+from .helpers import stream_with_context13 from .signals import before_render_template14 from .signals import template_rendered15 16 if t.TYPE_CHECKING: # pragma: no cover107 unmodified lines124 return list(result)125 126 127 def _render(template: Template, context: dict, app: "Flask") -> str:125- """Renders the template and fires the signal"""126-128 before_render_template.send(app, template=template, context=context)129 rv = template.render(context)130 template_rendered.send(app, template=template, context=context)131 return rv32 unmodified lines164 """165 ctx = _app_ctx_stack.top166 ctx.app.update_template_context(context)167 return _render(ctx.app.jinja_env.from_string(source), context, ctx.app)168+169+170+def _stream(171+ app: "Flask", template: Template, context: t.Dict[str, t.Any]172+) -> t.Iterator[str]:173+ app.update_template_context(context)174+ before_render_template.send(app, template=template, context=context)175+176+ def generate() -> t.Iterator[str]:177+ yield from template.generate(context)178+ template_rendered.send(app, template=template, context=context)179+180+ rv = generate()181+182+ # If a request context is active, keep it while generating.183+ if request:184+ rv = stream_with_context(rv)185+186+ return rv187+188+189+def stream_template(190+ template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]],191+ **context: t.Any192+) -> t.Iterator[str]:193+ """Render a template by name with the given context as a stream.194+ This returns an iterator of strings, which can be used as a195+ streaming response from a view.196+197+ :param template_name_or_list: The name of the template to render. If198+ a list is given, the first name to exist will be rendered.199+ :param context: The variables to make available in the template.200+201+ .. versionadded:: 2.2202+ """203+ app = current_app._get_current_object() # type: ignore[attr-defined]204+ template = app.jinja_env.get_or_select_template(template_name_or_list)205+ return _stream(app, template, context)206+207+208+def stream_template_string(source: str, **context: t.Any) -> t.Iterator[str]:209+ """Render a template from the given source string with the given210+ context as a stream. This returns an iterator of strings, which can211+ be used as a streaming response from a view.212+213+ :param source: The source code of the template to render.214+ :param context: The variables to make available in the template.215+216+ .. versionadded:: 2.2217+ """218+ app = current_app._get_current_object() # type: ignore[attr-defined]219+ template = app.jinja_env.from_string(source)220+ return _stream(app, template, context)modified: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:tests/test_templating.py+9 added
27 unmodified lines28 rv = client.get("/")29 assert rv.data == b"42"30 31 32+def test_simple_stream(app, client):33+ @app.route("/")34+ def index():35+ return flask.stream_template_string("{{ config }}", config=42)36+37+ rv = client.get("/")38+ assert rv.data == b"42"39+40+41 def test_request_less_rendering(app, app_ctx):42 app.config["WORLD_NAME"] = "Special World"43 44 @app.context_processor408 unmodified linesmodified:CHANGES.rst+4 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+- Add ``stream_template`` and ``stream_template_string`` functions to44+ render a template as a stream of pieces. :pr:`4629`45 46 47 Version 2.1.348 -------------1291 unmodified lines