如何不断更新flask中的变量

2024-06-02 06:19:58 发布

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

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

这是我的路线.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>

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

谢谢你的帮助


Tags: fromimportapp列表indextitlehtmltemplate
1条回答
网友
1楼 · 发布于 2024-06-02 06:19:58

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

考虑将{{CD2}}全局化,然后向其添加项:

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

相关问题 更多 >