Skip to content

Instantly share code, notes, and snippets.

@mvgolom
Forked from huiliu/app.py
Created January 21, 2022 01:26
Show Gist options
  • Save mvgolom/de0e25282beeb342af97763b0db0e7e7 to your computer and use it in GitHub Desktop.
Save mvgolom/de0e25282beeb342af97763b0db0e7e7 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 %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment