streaming.rst
This file
Path
docs/patterns/streaming.rst
100 lines · 3.2 KiB
Last changed by
Merge branch 'stable'David Lordbefore adoption3a9d54f
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.1011HTTP Response Behavior12----------------------1314**Headers cannot be changed after the streaming response starts.**1516When using streaming, it's important to be aware of the order than an HTTP17response is sent. All headers must be sent first, then the body. More headers18cannot be sent after the body has begun. Therefore, you must make sure all19headers are set before starting the response, outside the generator.2021In particular, if the generator will access ``session``, be sure to do so in the22view as well so that the ``Vary: cookie`` header will be set. Do not modify the23session in the generator, as the ``Set-Cookie`` header will already be sent.242526Basic Usage27-----------2829This is a basic view function that generates a lot of CSV data on the fly.30The trick is to have an inner function that uses a generator to generate31data and to then invoke that function and pass it to a response object::3233 @app.route('/large.csv')34 def generate_large_csv():35 def generate():36 for row in iter_all_rows():37 yield f"{','.join(row)}\n"38 return generate(), {"Content-Type": "text/csv"}3940Each ``yield`` expression is directly sent to the browser. Note though41that some WSGI middlewares might break streaming, so be careful there in42debug environments with profilers and other things you might have enabled.4344Streaming from Templates45------------------------4647The Jinja template engine supports rendering a template piece by48piece, returning an iterator of strings. Flask provides the49:func:`~flask.stream_template` and :func:`~flask.stream_template_string`50functions to make this easier to use.5152.. code-block:: python5354 from flask import stream_template5556 @app.get("/timeline")57 def timeline():58 return stream_template("timeline.html")5960The parts yielded by the render stream tend to match statement blocks in61the template.626364Streaming with Context65----------------------6667The :data:`.request` proxy will not be active while the generator is68running, because the app has already returned control to the WSGI server at that69point. If you try to access ``request``, you'll get a ``RuntimeError``.7071If your generator function relies on data in ``request``, use the72:func:`.stream_with_context` wrapper. This will keep the request context active73during the generator.7475.. code-block:: python7677 from flask import stream_with_context, request78 from markupsafe import escape7980 @app.route('/stream')81 def streamed_response():82 def generate():83 yield '<p>Hello '84 yield escape(request.args['name'])85 yield '!</p>'86 return stream_with_context(generate())8788It can also be used as a decorator.8990.. code-block:: python9192 @stream_with_context93 def generate():94 ...9596 return generate()9798The :func:`~flask.stream_template` and99:func:`~flask.stream_template_string` functions automatically100use :func:`~flask.stream_with_context` if a request is active.