Skip to content
Myr

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 file

Take it

The walk stopped after 200 commits: lines older than 73739a2 point at it.

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1–10why, one step back
1Streaming Contents
2==================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.10

Merge branch 'stable'David Lordbefore adoption3a9d54f

lines 11–25why, one step back
11HTTP Response Behavior
12----------------------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.2425

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 26–46why, one step back
26Basic Usage
27-----------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------------------------46

Merge branch 'stable'David Lordbefore adoption3301232

line 47why, one step back
47The Jinja template engine supports rendering a template piece by

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 48–66why, one step back
48piece, returning an iterator of strings. Flask provides the
49: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----------------------66

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 67–69why, one step back
67The :data:`.request` proxy will not be active while the generator is
68running, because the app has already returned control to the WSGI server at that69point. If you try to access ``request``, you'll get a ``RuntimeError``.

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 70–71why, one step back
70
71If your generator function relies on data in ``request``, use the

merge app and request context (#5812)David Lordbefore adoptionadf3636

lines 72–73why, one step back
72:func:`.stream_with_context` wrapper. This will keep the request context active
73during the generator.

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 74–100why, one step back
74
75.. 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.