streaming.rst
This file
Path
docs/patterns/streaming.rst
85 lines · 2.6 KiB
Last changed by
merge app and request context (#5812)David Lordbefore adoptionadf3636
History of this fileTake it
The walk stopped after 200 commits: lines older than eeebb5a point at it.
Merge branch '2.2.x'David Lordbefore adoptioneeebb5a
lines 1–31why, one step back1Streaming 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------------------------31Merge branch 'stable'David Lordbefore adoption3301232
line 32why, one step back32The Jinja template engine supports rendering a template piece byMerge branch '2.2.x'David Lordbefore adoptioneeebb5a
lines 33–51why, one step back33piece, 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----------------------51merge app and request context (#5812)David Lordbefore adoptionadf3636
lines 52–54why, one step back52The :data:`.request` proxy will not be active while the generator is53running, because the app has already returned control to the WSGI server at that54point. If you try to access ``request``, you'll get a ``RuntimeError``.Merge branch '2.2.x'David Lordbefore adoptioneeebb5a
lines 55–56why, one step back5556If your generator function relies on data in ``request``, use themerge app and request context (#5812)David Lordbefore adoptionadf3636
lines 57–58why, one step back57:func:`.stream_with_context` wrapper. This will keep the request context active58during the generator.Merge branch '2.2.x'David Lordbefore adoptioneeebb5a
lines 59–85why, one step back5960.. 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.