Skip to content

Instantly share code, notes, and snippets.

@huiliu
Created December 8, 2015 17:12
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save huiliu/46be335427605960fa84 to your computer and use it in GitHub Desktop.
Save huiliu/46be335427605960fa84 to your computer and use it in GitHub Desktop.
Flask Streaming from Templates
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask, stream_with_context, request, Response, flash
from time import sleep
app = Flask(__name__)
def stream_template(template_name, **context):
app.update_template_context(context)
t = app.jinja_env.get_template(template_name)
rv = t.stream(context)
rv.disable_buffering()
return rv
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
def generate():
for item in data:
yield str(item)
sleep(1)
@app.route('/stream')
def stream_view():
rows = generate()
return Response(stream_template('template.html', rows=rows))
if __name__ == '__main__':
app.debug = True
app.run()
{% for item in rows %}
<h1>{{ item }}</h1>
{% endfor %}
@vmax
Copy link

vmax commented Mar 19, 2017

Nice gist, but return Response(stream_with_context(stream_template('template.html', rows=rows))) should be added

@dominikstraessle
Copy link

Exactly what I searched for, thank you.

@zheng-xing
Copy link

Thanks! Solved my problem.

@doctornuclear
Copy link

Thanks man! Really helped me stream my contents on the website while the processing is being done on the backend!

@stolarczyk
Copy link

Note: need to put template.html in a templates directory for Flask to find it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment