Skip to content

Instantly share code, notes, and snippets.

@jinuljt
Last active August 22, 2017 04:11
Show Gist options
  • Select an option

  • Save jinuljt/d67b9d5c30ea6b8756b2c806a57aba38 to your computer and use it in GitHub Desktop.

Select an option

Save jinuljt/d67b9d5c30ea6b8756b2c806a57aba38 to your computer and use it in GitHub Desktop.
flask 使用模板 stream 每次返回一块数据

参考:http://flask.pocoo.org/docs/0.12/patterns/streaming/#streaming-from-templates

目录结构:
.
├── app.py
└── templates
    └── the_template.html

run

FLASK_APP=app.py flask run

app.py

from flask import Response, Flask


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


@app.route('/t')
def render_large_template():
    rows = [1,2,3,4]
    return Response(stream_template('the_template.html', rows=rows))

the_templates.html

{% for row in rows %}
    {{ row }}
{% endfor %}

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