簡體   English   中英

用Flask流式傳輸帶有靜態內容的模板

[英]Streaming a template with static content with Flask

此示例之后 ,我正在嘗試使用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同時渲染流和靜態內容?

你可以試試這個嗎?

from flask import Response, stream_with_context

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

我遍歷了stackoverflow上的所有帖子后發現了這一點,並使其正常工作。 另外,我認為您應該在iter_all_rows()函數中使用yield

參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM