Skip to content
Myr

Direct passthrough is counter productive

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 81b4271 · Browse files · 1 file+3 added−8 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+3 added−8 removed

  • other:+3 added−8 removed

1 file+3 added−8 removed

modified:docs/patterns/streaming.rst+3 added-8 removed
11 unmodified lines
12-----------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::16data 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'28 return Response(generate(), direct_passthrough=True,29 mimetype='text/csv')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.
16 unmodified lines
4647 @app.route('/my-large-page.html')48 def render_large_template():49 rows = iter_all_rows()54 return Response(stream_template('the_template.html', rows=rows),55 direct_passthrough=True)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 a
7 unmodified lines