streaming.rst
This file
Path
docs/patterns/streaming.rst
84 lines · 3.1 KiB
Last changed by
Added flask.stream_with_contextArmin Ronacherbefore adoptiond521899
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 from flask import Response1920 @app.route('/large.csv')21 def generate_large_csv():22 def generate():23 for row in iter_all_rows():24 yield ','.join(row) + '\n'25 return Response(generate(), mimetype='text/csv')2627Each ``yield`` expression is directly sent to the browser. Now though28that some WSGI middlewares might break streaming, so be careful there in29debug environments with profilers and other things you might have enabled.3031Streaming from Templates32------------------------3334The Jinja2 template engine also supports rendering templates piece by35piece. This functionality is not directly exposed by Flask because it is36quite uncommon, but you can easily do it yourself::3738 from flask import Response3940 def stream_template(template_name, **context):41 app.update_template_context(context)42 t = app.jinja_env.get_template(template_name)43 rv = t.stream(context)44 rv.enable_buffering(5)45 return rv4647 @app.route('/my-large-page.html')48 def render_large_template():49 rows = iter_all_rows()50 return Response(stream_template('the_template.html', rows=rows))5152The trick here is to get the template object from the Jinja2 environment53on the application and to call :meth:`~jinja2.Template.stream` instead of54:meth:`~jinja2.Template.render` which returns a stream object instead of a55string. Since we're bypassing the Flask template render functions and56using the template object itself we have to make sure to update the render57context ourselves by calling :meth:`~flask.Flask.update_template_context`.58The template is then evaluated as the stream is iterated over. Since each59time you do a yield the server will flush the content to the client you60might want to buffer up a few items in the template which you can do with61``rv.enable_buffering(size)``. ``5`` is a sane default.6263Streaming with Context64----------------------6566.. versionadded:: 0.96768Note that when you stream data, the request context is already gone the69moment the function executes. Flask 0.9 provides you with a helper that70can keep the request context around during the execution of the71generator::7273 from flask import stream_with_context, request, Response7475 @app.route('/stream')76 def streamed_response():77 def generate():78 yield 'Hello '79 yield request.args['name']80 yield '!'81 return Response(stream_with_context(generate()))8283Without the :func:`~flask.stream_with_context` function you would get a84:class:`RuntimeError` at that point.