Home > Software design >  Python Flask ephemeral variable
Python Flask ephemeral variable

Time:03-13

I'm currently programming a decoding game in Python with an HTML interface using Flask. There is a mode where users can freely decode the words and I want to implement a point system (every time the correct answer is given, the point counter will increase). Here is what I did:

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)

The first problem (that I have managed to solve) was that whenever the user submitted his answer, this function would run once again so the previous word to decode was forgotten by the program : I replaced simple ints / strings by 2-uplets with the previous datas and the new ones. But a problem persists : the point counter doesn't reset when the user leaves the game and remains in memory (while I want the point system to be ephemeral)... Is there a way to reset this variable when the user leaves the game (and therefore changes of route) ? I hope I have been clear, thank you for your help

CodePudding user response:

I can't run code but maybe you should use GET to generate new word and reset points. This is how most pages work.

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)

BTW:

if you want to run for many users at the same time then you may need to keep it in dictionary with unique SessionID for every user. You could generate it in GET and send it as hidden <input> in form. And resend it in every POST. Or you could use flask.session.

  • Related