【问题标题】:How can I yield a template over another in flask?如何在烧瓶中生成一个模板而不是另一个模板?
【发布时间】:2019-09-08 05:31:36
【问题描述】:

我一直在从事烧瓶中的一个项目,但我被困在一个地方,我需要弄清楚如何产生一个烧瓶模板而不是另一个。

为了说明我的意思,例如,我有一个这样的程序。

main.py

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)

index.html

<h3>Hi</h3>

index2.html

<h3>Bye</h3>

运行 main.py 返回:

Hi
Bye

尽管这是有道理的,但我的目标是让它只产生Bye,它应该替换Hi。我尝试了其他路径,例如返回两者,但它们都没有奏效。关于如何做到这一点的任何想法?

【问题讨论】:

  • 我认为您不了解生成器的工作原理...它需要通过迭代或next 来调用。
  • @Error-SyntacticalRemorse 是的,我也是这么想的,在这种情况下使用生成器是不正确的,但是当我返回两个没有生成器的文件时,只有第一个文件的内容可见。如果你不介意,你能告诉我你说在这个特定场景中使用迭代或next 函数是什么意思吗?

标签: python python-3.x flask


【解决方案1】:

这不是你的情况,但如果你想流式传输具有静态内容的模板,这里有一种方法。我将使用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()

templates/index.html

{% for item in rows %}
<h1>{{ item }}</h1>
{% endfor %}

请参阅文档中的streaming from templates

【讨论】:

【解决方案2】:

你必须做不同的功能才能使用这样的生成器。

from flask import Flask, stream_with_context, Response, render_template
app = Flask('app')

def page_generator():
    yield render_template('index.html')
    yield render_template('index2.html')
generator_obj = None

@app.route('/')
def hello_world():
    global generator_obj
    generator_obj = generator_obj or page_generator()
    return Response(stream_with_context(next(generator_obj)))

app.run(host='0.0.0.0', port=8080)

我不确定这是否适用于烧瓶。 请注意,在您调用 hello_world 两次之后,这将失败,除非您在 StopIteration 上将 generator_obj 重置为 None

【讨论】:

  • 它就像Hi 一样工作,然后我必须重新加载才能显示Bye。关于如何在不重新加载的情况下执行此操作的任何线索?
  • 这就是生成器的工作原理......它需要调用该方法两次......如果你想在一段时间后加载第二个页面,你应该在谷歌上搜索一下。
  • 好的,谢谢你的帮助。我会接受这个答案,因为它确实帮助我解决了加载第二个模板的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-14
  • 2012-06-14
  • 1970-01-01
  • 2016-07-06
  • 1970-01-01
相关资源
最近更新 更多