用Flas流式传输静态内容模板

2024-03-29 10:53:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用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

^{pr2}$

到目前为止,流式处理很好,,但静态内容在流完成之前不会呈现。如何让Flask在流开始时立即呈现流和静态内容?在


Tags: thenameappflaskstreamreturnresponsedef
1条回答
网友
1楼 · 发布于 2024-03-29 10:53:10

你能试试这个吗?在

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

相关问题 更多 >