pro*_*llz 2 python flask python-3.x
我一直在研究烧瓶中的一个项目,我被困在需要弄清楚如何产生一个烧瓶模板而不是另一个的部分上。
例如,为了说明我的意思,我有一个这样的程序。
主文件
from flask import Flask, stream_with_context, Response, render_template
app = Flask('app')
@app.route('/')
def hello_world():
def generate():
yield render_template('index.html')
yield render_template('index2.html')
return Response(stream_with_context(generate()))
app.run(host='0.0.0.0', port=8080)
Run Code Online (Sandbox Code Playgroud)
索引.html
<h3>Hi</h3>
Run Code Online (Sandbox Code Playgroud)
索引2.html
<h3>Bye</h3>
Run Code Online (Sandbox Code Playgroud)
运行 main.py 返回:
Hi
Bye
Run Code Online (Sandbox Code Playgroud)
尽管这是有道理的,但我的目标是使其结果恰好Bye取代Hi. 我尝试了其他路径,例如返回两者,但都没有奏效。关于我如何做到这一点的任何想法?
这不是你的情况,但如果你想流式传输包含静态内容的模板,这里有一种方法。我将使用该sleep()方法暂停执行 1 秒。
from flask import Flask, stream_with_context, request, Response, flash
import time
from time import sleep
app = Flask(__name__)
def stream_template(template_name, **context):
app.update_template_context(context)
t = app.jinja_env.get_template(template_name)
rv = t.stream(context)
rv.disable_buffering()
return rv
data = ['Hi', 'Bye']
def generate():
for item in data:
yield str(item)
sleep(1)
@app.route('/')
def stream_view():
rows = generate()
return Response(stream_with_context(stream_template('index.html', rows=rows)))
if __name__ == "__main__":
app.run()
Run Code Online (Sandbox Code Playgroud)
其中模板/index.html:
{% for item in rows %}
<h1>{{ item }}</h1>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
请参阅文档中的模板流式传输。
| 归档时间: |
|
| 查看次数: |
3170 次 |
| 最近记录: |