Skip to content

Instantly share code, notes, and snippets.

@huiliu
Created December 8, 2015 17:12
Show Gist options
  • 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 %}
@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