streaming.rst
This file
Path
docs/patterns/streaming.rst
85 lines · 2.6 KiB
Last changed by
Merge pull request #4629 from pgjones/generateDavid Lordbefore adoptionab36542
History of this fileTake it
1Streaming Contents2==================34Sometimes you want to send an enormous amount of data to the client, much5more than you want to keep in memory. When you are generating the data on6the fly though, how do you send that back to the client without the7roundtrip to the filesystem?89The answer is by using generators and direct responses.1011Basic Usage12-----------1314This is a basic view function that generates a lot of CSV data on the fly.15The trick is to have an inner function that uses a generator to generate16data and to then invoke that function and pass it to a response object::1718 @app.route('/large.csv')19 def generate_large_csv():20 def generate():21 for row in iter_all_rows():22 yield f"{','.join(row)}\n"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 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.3637.. code-block:: python3839 from flask import stream_template4041 @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----------------------5152The :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``.5556If 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():68 yield '<p>Hello '69 yield escape(request.args['name'])70 yield '!</p>'71 return stream_with_context(generate())7273It 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.