Flask session variables

后端 未结 3 1685
眼角桃花
眼角桃花 2021-02-03 15:31

I\'m writing a small web app with flask. I have a problem with session variables when two users (under the same network) try to use app.

This is the code:



        
相关标签:
3条回答
  • 2021-02-03 15:41

    Using randint(0,4) to generate number means that they will sometimes be equal for different users. To generate unique number every time use uuid:

    from uuid import uuid4
    def random():
        session['number'] = str(uuid4())
        return None
    

    or generator:

    import itertools
    consequent_integers = itertools.count()
    
    def random():
        session['number'] = consequent_integers.next()
        return None
    
    0 讨论(0)
  • 2021-02-03 15:54

    The reason that the session variable is the same for the two users is likely because you're using the same computer / browsing account. It's just like how Facebook remembers your login status after you open a new Facebook tab.

    I advise you to get another computer or use a different Chrome Account (top right of Google Chrome) to test out for different users.

    0 讨论(0)
  • 2021-02-03 15:56

    So you do something like this. It is not tested but should work. You retrieve the current username and the numbers dictionary from the session variable. Check if there is an existing value for the current username. If not create a random number and save it in the session. Else just use the saved value.

    @app.route('/check', methods=['GET', 'POST'])
    def check():
    
       # retrieve current username and numbers from your session
       username = session['username']
       numbers = session.get('numbers', {})
    
       # if no number is existing create a new one and save it to session
       if username not in numbers:
           number = randint(0,4)
           numbers['username'] = number
           session['numbers'] = numbers
       else:
           number = numbers['username']
    
       return render_template('file.html', number=number, user=username)
    
    0 讨论(0)
提交回复
热议问题