Search code examples
flasksessionflask-sqlalchemyflask-socketio

Flask-Socketio Session returning last value


server-side

@app.route('/login',methods=['GET','POST'])
def login():        
    if request.method == 'POST':
        if Users.is_user(request.form['username'],request.form['password']):
            name = Users.get_name(request.form['username'])
            session['name'] = name
            return redirect(url_for('home'))
        else:
            return redirect(url_for('login'))   
return render_template("login.html",**{'session':session})

@app.route('/get_name',methods=['GET'])
def get_name():
    data = {'name' : ''}
    if NAME_KEY in session:
        data = {'name':session['name']}
    return jsonify(data)

client-side

async function get_Name(){
    return fetch("/get_name")
    .then(function (response) {
        return  response.json();   
      })
      .then(function (text) {
        return text["name"];
      });
}
   socket.on('message', async function(msg) {
   let user_name =  await get_Name();
   $("#messages").append('<li>'+user_name+':'+msg+'</li>');
   console.log('Received message');
  });
});

When the last user logs in, the Username of all users changes to the last Username. But in logs, I can see that session['name'] is specific to the user logged in.


Solution

  • $('#sendbutton').on('click', async function() {
    var user_name =  await get_Name();
    var msg = $('#myMessage').val()
    var data = {
        'name': user_name,
        'msg' : msg
    };
    socket.emit('message',data);
    $('#myMessage').val('');
    });
    

    I used emit to send data that contains the name of the user sending the message and again sent that to javascript via an emit function in python.