Python Flask 临时变量

Python Flask ephemeral variable

我目前正在 Python 中使用 Flask 使用 HTML 界面编写解码游戏。有一种模式,用户可以自由解码单词,我想实现一个积分系统(每次给出正确答案,积分计数器都会增加)。这是我所做的:

shift=[0,0]
word=["",""]
points=0
@app.route('/l_cesar', methods=['GET', 'POST'])
def l_cesar():
    global shift, word, points
    shift[0]=shift[1]
    shift[1]=randint(1,26)
    word[0]=word[1]
    word[1]=''.join(cryptage.cesar(choice(cryptage.get_d(2)), shift[1]))
    if request.method=='POST':
        inputword=request.form['word']
        if cryptage.cesar(inputword, shift[0])==word[0]:
            points+=1
    return render_template('l_cesar.html', word=word[1], shift=shift[1], points=points)

第一个问题(我已经设法解决)是每当用户提交他的答案时,这个函数会再次运行所以程序忘记了之前要解码的单词:我替换了简单整数/字符串由 2-uplets 与以前的数据和新数据组成。 但问题仍然存在:当用户离开游戏并保留在内存中时,积分计数器不会重置(虽然我希望积分系统是短暂的)...... 当用户离开游戏(并因此改变路线)时,有没有办法重置这个变量?我希望我已经清楚了,谢谢你的帮助

我不会 运行 代码,但也许你应该使用 GET 来生成新词和重置点。
这就是大多数页面的工作方式。

shift = 0
word = ""
points = 0

@app.route('/l_cesar', methods=['GET', 'POST'])
def l_cesar():
    global shift, word, points
    
    if request.method == 'GET':
        word = ''.join(cryptage.cesar(choice(cryptage.get_d(2)), shift))
        points = 0
        
    if request.method == 'POST':
        inputword = request.form['word']
        if cryptage.cesar(inputword, shift) == word:
            points+=1
            
    return render_template('l_cesar.html', word=word, shift=shift, points=points)

顺便说一句:

如果你想同时为许多用户 运行 那么你可能需要将它保存在字典中,每个用户都有唯一的 SessionID 。您可以在 GET 中生成它并将其作为隐藏的 <input> 形式发送。并每隔 POST 重新发送一次。或者你可以使用 flask.session.