add generate_template and generate_template_string functions
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 762382e · Browse files · 7 files·+139 added−37 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+139 added−37 removed
- tests:+9 added−0 removed
- other:+130 added−37 removed
Provenance
- Commit
46433e9- Tree
6cc0ca3- Author
pgjones <philip.graham.jones@googlemail.com>- Committer
David Lord <davidism@gmail.com>- Parent
762382e
7 files changed+139 added−37 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/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: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+2 added
38 unmodified lines39 - ``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