【问题标题】:How to constantly update a variable in flask [duplicate]如何不断更新烧瓶中的变量[重复]
【发布时间】:2021-04-01 09:17:22
【问题描述】:

我想通过在其中添加更多“东西”来不断更新我的列表stuff。但是,我的列表没有更新(最好每秒更新一次,但我不知道如何在烧瓶中执行 while 循环)。

这是我的 routes.py :

from flask import render_template
from app import app
from win32gui import GetWindowText, GetForegroundWindow

@app.route('/')
@app.route('/index')
def index():
    user = {'username': 'Miguel'}
    stuff = []
    stuff.append(GetWindowText(GetForegroundWindow()))
    return render_template('index.html', title='Home', user=user, stuff = stuff)

if __name__ == "__main__":
    app.run(debug=True)

这是我的 index.html :

<html>
    <head>
        {% if title %}
        <title>{{ title }} - Microblog</title>
        {% else %}
        <title>Welcome to Microblog!</title>
        {% endif %}
    </head>
    <body>
        <h1>Hello, {{ user.username }}!</h1>
        <h1>Here: </h1>
        {% for item in stuff %}
            <p> {{ item }} </p>
        {% endfor %}
    </body>
</html>

当我flask run 时,列表中只有一项。如何让程序知道我想继续添加更多项目?我想在index() 函数中实现这一点。

感谢您的帮助!

【问题讨论】:

    标签: python html python-3.x flask while-loop


    【解决方案1】:

    每次调用 index 方法时,局部变量 stuff 都会重新初始化为一个空列表,然后您将一个元素附加到它。这就是为什么每次刷新页面时,在stuff 中只能看到这个新添加的元素。

    考虑将stuff 设为全局,然后向其中添加项目:

    from flask import render_template
    from app import app
    from win32gui import GetWindowText, GetForegroundWindow
    
    stuff = []
    
    @app.route('/')
    @app.route('/index')
    def index():
        global stuff
        user = {'username': 'Miguel'}
        stuff.append(GetWindowText(GetForegroundWindow()))
        return render_template('index.html', title='Home', user=user, stuff = stuff)
    
    if __name__ == "__main__":
        app.run(debug=True)
    

    或者将全局变量存储在better way中。

    【讨论】:

    • 非常感谢,这对您很有帮助!
    • 我一直在想,我如何让它每秒都附加信息,而不仅仅是每次刷新页面时? @贾维斯
    • 您可以简单地将追加内容放在while True 中,然后将time.sleep(1) 追加到那里的内容中。但是由于您想每秒增加一次,您应该考虑转移到其他一些函数,因为它不再与index 相关。您可以在函数中生成一个线程 (daemon=True),在此之前将运行无限 while 循环,休眠 1 秒,然后将元素附加到列表中。
    • 感谢您的回复!那么我应该在 While 循环中使用另一个函数,然后在索引中调用该函数吗?由于 while 循环可能会永远持续下去并且不会返回任何值,这会起作用吗?
    • 不会的,这就是为什么这个方法应该从作为后台守护进程运行的线程中调用。该线程将使用无限 while 循环调用该方法,您可以在 main 方法本身中生成该线程。查看 Python 线程文档以了解它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 2018-04-08
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多