Created
December 8, 2015 17:12
-
-
Save huiliu/46be335427605960fa84 to your computer and use it in GitHub Desktop.
Flask Streaming from Templates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% for item in rows %} | |
<h1>{{ item }}</h1> | |
{% endfor %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: need to put
template.html
in a templates directory for Flask to find it.