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

问题描述 投票:0回答:1

我正在尝试使用Flask流式传输模板,遵循this example。所以,我的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同时呈现流和静态内容?

python flask jinja2 werkzeug
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.