Skip to content
Myr

Merge pull request #3659 from iomintz/patch-1

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

[docs] streaming contents: use app.response_class

authored by David Lord · committed by GitHub · parents ecd07d6, 92f648b · Browse files · 1 file+4 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+4 added−8 removed

  • other:+4 added−8 removed

1 file+4 added−8 removed

modified:docs/patterns/streaming.rst+4 added-8 removed
13 unmodified lines
14This 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 Response1918 @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"25 return Response(generate(), mimetype='text/csv')23 return app.response_class(generate(), mimetype='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.
4 unmodified lines
32The 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::3538 from flask import Response3936 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)
2 unmodified lines
4243 @app.route('/my-large-page.html')44 def render_large_template():45 rows = iter_all_rows()50 return Response(stream_template('the_template.html', rows=rows))46 return app.response_class(stream_template('the_template.html', rows=rows))4748The 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 a
14 unmodified lines
65moment the function executes. Flask 0.9 provides you with a helper that66can keep the request context around during the execution of the67generator::6873 from flask import stream_with_context, request, Response69 from flask import stream_with_context, request7071 @app.route('/stream')72 def streamed_response():73 def generate():74 yield 'Hello '75 yield request.args['name']76 yield '!'81 return Response(stream_with_context(generate()))77 return app.response_class(stream_with_context(generate()))7879Without the :func:`~flask.stream_with_context` function you would get a80:class:`RuntimeError` at that point.