使用Flask使用静态内容流式传输模板

时间:2018-04-08 17:23:14

标签: python flask jinja2 werkzeug

我在this example之后尝试使用Flask流式传输模板。所以,我的app.py看起来像是:

from flask import Response

def stream_template(template_name, **context):
    app.update_template_context(context)
    t = app.jinja_env.get_template(template_name)
    rv = t.stream(context)
    rv.enable_buffering(5)
    return rv

@app.route('/my-large-page.html')
def render_large_template():
    rows = iter_all_rows()
    return Response(stream_template('the_template.html', rows=rows))

我的the_template.html

<p>This is some static content:</p>
<img src="{{ url_for('static', filename='logo.png') }}"/>

<p>This is some streamed content:</p>
{% for row in rows %}
<p>{{ row }}</p>
{% endfor %}

到目前为止,流式传输工作正常,但静态内容在流完成后才会呈现。如何在流开始时告诉Flask同时呈现流和静态内容?

1 个答案:

答案 0 :(得分:0)

你可以试试吗?

from flask import Response, stream_with_context

return Response(stream_with_context(stream_template('the_template.html', rows=rows)))

我在研究了stackoverflow上的所有帖子后才发现这一点,并使其正常工作。 另外,我认为您应该在yield函数中使用iter_all_rows()

Reference