streaming.rst
This file
Path
docs/patterns/streaming.rst
66 lines · 2.7 KiB
Last changed by
No need for the directive here.Armin Ronacherbefore adoption029eebe
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 object17that has the ``direct_passthrough`` flag set. This flag is used to inform18the system that data is generated on the fly and should be passed through19without buffering::2021 from flask import Response2223 @app.route('/large.csv')24 def generate_large_csv():25 def generate():26 for row in iter_all_rows():27 yield ','.join(row) + '\n'28 return Response(generate(), direct_passthrough=True,29 mimetype='text/csv')3031Each ``yield`` expression is directly sent to the browser. Now though32that some WSGI middlewares might break streaming, so be careful there in33debug environments with profilers and other things you might have enabled.3435Streaming from Templates36------------------------3738The Jinja2 template engine also supports rendering templates piece by39piece. This functionality is not directly exposed by Flask because it is40quite uncommon, but you can easily do it yourself::4142 from flask import Response4344 def stream_template(template_name, **context):45 app.update_template_context(context)46 t = app.jinja_env.get_template(template_name)47 rv = t.stream(context)48 rv.enable_buffering(5)49 return rv5051 @app.route('/my-large-page.html')52 def render_large_template():53 rows = iter_all_rows()54 return Response(stream_template('the_template.html', rows=rows),55 direct_passthrough=True)5657The trick here is to get the template object from the Jinja2 environment58on the application and to call :meth:`~jinja2.Template.stream` instead of59:meth:`~jinja2.Template.render` which returns a stream object instead of a60string. Since we're bypassing the Flask template render functions and61using the template object itself we have to make sure to update the render62context ourselves by calling :meth:`~flask.Flask.update_template_context`.63The template is then evaluated as the stream is iterated over. Since each64time you do a yield the server will flush the content to the client you65might want to buffer up a few items in the template which you can do with66``rv.enable_buffering(size)``. ``5`` is a sane default.