【问题标题】:Streaming a template with static content with Flask使用 Flask 流式传输具有静态内容的模板
【发布时间】:2018-09-18 02:58:18
【问题描述】:

我正在尝试使用 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】:

    你可以试试这个吗?

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

    我在浏览了 stackoverflow 上的所有帖子后发现了这一点,并让它发挥了作用。 另外,我认为你应该在iter_all_rows()函数中使用yield

    Reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-19
      • 2012-03-08
      • 1970-01-01
      • 1970-01-01
      • 2017-12-11
      • 2015-12-13
      • 2012-09-01
      • 1970-01-01
      相关资源
      最近更新 更多