Skip to content
Myr

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

11 files+187 added−39 removed

modified:docs/patterns/streaming.rst+40 added-35 removed
18 unmodified lines
19 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")2425Each ``yield`` expression is directly sent to the browser. Note though26that some WSGI middlewares might break streaming, so be careful there in27debug environments with profilers and other things you might have enabled.2829Streaming from Templates30------------------------3132The Jinja2 template engine also supports rendering templates piece by33piece. This functionality is not directly exposed by Flask because it is34quite uncommon, but you can easily do it yourself::32The Jinja2 template engine supports rendering a template piece by33piece, returning an iterator of strings. Flask provides the34:func:`~flask.stream_template` and :func:`~flask.stream_template_string`35functions to make this easier to use.3636 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:: python3843 @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_template4048The trick here is to get the template object from the Jinja2 environment49on the application and to call :meth:`~jinja2.Template.stream` instead of50:meth:`~jinja2.Template.render` which returns a stream object instead of a51string. Since we're bypassing the Flask template render functions and52using the template object itself we have to make sure to update the render53context ourselves by calling :meth:`~flask.Flask.update_template_context`.54The template is then evaluated as the stream is iterated over. Since each55time you do a yield the server will flush the content to the client you56might 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")4445The parts yielded by the render stream tend to match statement blocks in46the template.474849Streaming with Context50----------------------5162.. versionadded:: 0.952The :data:`~flask.request` will not be active while the generator is53running, because the view has already returned at that point. If you try54to access ``request``, you'll get a ``RuntimeError``.5564Note that when you stream data, the request context is already gone the65moment the function executes. Flask 0.9 provides you with a helper that66can keep the request context around during the execution of the67generator::56If your generator function relies on data in ``request``, use the57:func:`~flask.stream_with_context` wrapper. This will keep the request58context active during the generator.5960.. code-block:: python6162 from flask import stream_with_context, request63 from markupsafe import escape6465 @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())7279Without the :func:`~flask.stream_with_context` function you would get a80:class:`RuntimeError` at that point.73It can also be used as a decorator.7475.. code-block:: python7677 @stream_with_context78 def generate():79 ...8081 return generate()8283The :func:`~flask.stream_template` and84:func:`~flask.stream_template_string` functions automatically85use :func:`~flask.stream_with_context` if a request is active.
modified:docs/api.rst+4 added
285 unmodified lines
286.. autofunction:: render_template287288.. autofunction:: render_template_string289290.. autofunction:: stream_template291292.. autofunction:: stream_template_string293294.. autofunction:: get_template_attribute295296Configuration297-------------
480 unmodified lines
modified:docs/templating.rst+26 added
199 unmodified lines
200201You could also build `format_price` as a template filter (see202:ref:`registering-filters`), but this demonstrates how to pass functions in a203context processor.204205Streaming206---------207208It can be useful to not render the whole template as one complete209string, instead render it as a stream, yielding smaller incremental210strings. This can be used for streaming HTML in chunks to speed up211initial page load, or to save memory when rendering a very large212template.213214The Jinja2 template engine supports rendering a template piece215by piece, returning an iterator of strings. Flask provides the216:func:`~flask.stream_template` and :func:`~flask.stream_template_string`217functions to make this easier to use.218219.. code-block:: python220221 from flask import stream_template222223 @app.get("/timeline")224 def timeline():225 return stream_template("timeline.html")226227These functions automatically apply the228:func:`~flask.stream_with_context` wrapper if a request is active, so229that it remains available in the template.
modified:src/flask/__init__.py+2 added
39 unmodified lines
40from .signals import signals_available as signals_available41from .signals import template_rendered as template_rendered42from .templating import render_template as render_template43from .templating import render_template_string as render_template_string44from .templating import stream_template as stream_template45from .templating import stream_template_string as stream_template_string4647__version__ = "2.2.0.dev0"
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/templating.py+56 added-2 removed
5 unmodified lines
6from jinja2 import TemplateNotFound78from .globals import _app_ctx_stack9from .globals import _request_ctx_stack10from .globals import current_app11from .globals import request12from .helpers import stream_with_context13from .signals import before_render_template14from .signals import template_rendered1516if t.TYPE_CHECKING: # pragma: no cover
107 unmodified lines
124 return list(result)125126127def _render(template: Template, context: dict, app: "Flask") -> str:125 """Renders the template and fires the signal"""126128 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 rv
32 unmodified lines
164 """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)168169170def _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)175176 def generate() -> t.Iterator[str]:177 yield from template.generate(context)178 template_rendered.send(app, template=template, context=context)179180 rv = generate()181182 # If a request context is active, keep it while generating.183 if request:184 rv = stream_with_context(rv)185186 return rv187188189def 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.196197 :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.200201 .. 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)206207208def 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.212213 :param source: The source code of the template to render.214 :param context: The variables to make available in the template.215216 .. 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 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:tests/test_templating.py+9 added
27 unmodified lines
28 rv = client.get("/")29 assert rv.data == b"42"303132def test_simple_stream(app, client):33 @app.route("/")34 def index():35 return flask.stream_template_string("{{ config }}", config=42)3637 rv = client.get("/")38 assert rv.data == b"42"394041def test_request_less_rendering(app, app_ctx):42 app.config["WORLD_NAME"] = "Special World"4344 @app.context_processor
408 unmodified lines
modified:CHANGES.rst+4 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`43- Add ``stream_template`` and ``stream_template_string`` functions to44 render a template as a stream of pieces. :pr:`4629`454647Version 2.1.348-------------
1291 unmodified lines