streaming.rst
This file
Path
docs/patterns/streaming.rst
80 lines · 3.0 KiB
Last changed by
Merge pull request #3659 from iomintz/patch-1David Lordbefore adoption9075da1
History of this fileTake it
The walk stopped after 200 commits: lines older than fcc0d6e point at it.
Merge pull request #3647 from pallets/dependabot/pip/pre-commit-2.5.0dependabot-preview[bot]before adoptionfcc0d6e
lines 1–22why, 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"Merge pull request #3659 from iomintz/patch-1David Lordbefore adoption9075da1
line 23why, one step back23 return app.response_class(generate(), mimetype='text/csv')Merge pull request #3647 from pallets/dependabot/pip/pre-commit-2.5.0dependabot-preview[bot]before adoptionfcc0d6e
lines 24–45why, one step back2425Each ``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------------------------3132The Jinja2 template engine also supports rendering templates piece by33piece. This functionality is not directly exposed by Flask because it is34quite uncommon, but you can easily do it yourself::3536 def stream_template(template_name, **context):37 app.update_template_context(context)38 t = app.jinja_env.get_template(template_name)39 rv = t.stream(context)40 rv.enable_buffering(5)41 return rv4243 @app.route('/my-large-page.html')44 def render_large_template():45 rows = iter_all_rows()Merge pull request #3659 from iomintz/patch-1David Lordbefore adoption9075da1
line 46why, one step back46 return app.response_class(stream_template('the_template.html', rows=rows))Merge pull request #3647 from pallets/dependabot/pip/pre-commit-2.5.0dependabot-preview[bot]before adoptionfcc0d6e
lines 47–68why, one step back4748The trick here is to get the template object from the Jinja2 environment49on the application and to call :meth:`~jinja2.Template.stream` instead of50:meth:`~jinja2.Template.render` which returns a stream object instead of a51string. Since we're bypassing the Flask template render functions and52using the template object itself we have to make sure to update the render53context ourselves by calling :meth:`~flask.Flask.update_template_context`.54The template is then evaluated as the stream is iterated over. Since each55time you do a yield the server will flush the content to the client you56might want to buffer up a few items in the template which you can do with57``rv.enable_buffering(size)``. ``5`` is a sane default.5859Streaming with Context60----------------------6162.. versionadded:: 0.96364Note that when you stream data, the request context is already gone the65moment the function executes. Flask 0.9 provides you with a helper that66can keep the request context around during the execution of the67generator::68Merge pull request #3659 from iomintz/patch-1David Lordbefore adoption9075da1
line 69why, one step back69 from flask import stream_with_context, requestMerge pull request #3647 from pallets/dependabot/pip/pre-commit-2.5.0dependabot-preview[bot]before adoptionfcc0d6e
lines 70–76why, one step back7071 @app.route('/stream')72 def streamed_response():73 def generate():74 yield 'Hello '75 yield request.args['name']76 yield '!'Merge pull request #3659 from iomintz/patch-1David Lordbefore adoption9075da1
line 77why, one step back77 return app.response_class(stream_with_context(generate()))Merge pull request #3647 from pallets/dependabot/pip/pre-commit-2.5.0dependabot-preview[bot]before adoptionfcc0d6e
lines 78–80why, one step back7879Without the :func:`~flask.stream_with_context` function you would get a80:class:`RuntimeError` at that point.