Flask session variables

24,957

Solution 1

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

Solution 2

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)
Share:
24,957
Teor9300
Author by

Teor9300

Updated on July 09, 2022

Comments

  • Teor9300
    Teor9300 almost 2 years

    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:

    import os
    
    from flask import Flask, request, render_template, g, session
    from random import randint
    
    def random():
         session['number'] = randint(0,4)
         return None
    
    @app.route('/')
    def home():
      if not session.get('logged_in'):
        return render_template('login.html')
      else: 
        return check()
    
    @app.route('/login', methods = ['GET', 'POST'])
    def login():
          global username
          username = request.form['username']
          session['logged_in'] = True
          session['username'] = username
          return check()
    
    @app.route('/check', methods=['GET', 'POST'])
    def check():
           random()
           return render_template('file.html', number = session['number'], user = session['username'])
    
    if __name__ == "__main__":
        app.secret_key = ".."
        app.run(host = '0.0.0.0',port = 3134, debug=False)
    

    In file.html there is a button type "submit" that call '/check' route. The problem is when two users use app at same time because the variable 'number' is equal to variable 'number' of the last user that push the button... there isn't indipendence between two sessions.

    I would that the two users has two indipendence sessions, like if they use my app in local host.

  • Teor9300
    Teor9300 almost 7 years
    Yes i want that the numbers can be equal for different users. But i don't want that the number of user1 change when user2 do a request of a new number... Example: User 1 run app and his number is 3, then user2 run app and his number is 6... when user1 surf in other page of app i don't want that his number became 6 like happen in my app. Do you understand my problem?
  • Fine
    Fine almost 7 years
    From my point of you, your problem could be that any action on your web-service leads to generation of new number. As I can see, you should move random() from check() to login().
  • cardamom
    cardamom almost 6 years
    Am also using this functionality for the first time and learning about it. Why here numbers = session.get('numbers', {}) if no session, assign an empty dictionary rather than None for example. If there is a session it returns a string, so not sure there is any logic to it returning an empty dictionary if there is not one..