user2699190 user2699190 -4 years ago 194
Python Question

flask socketio session query string

this code is supposed to work, but it does not work

As soon as a client connects, the session 'keyo' is assigned to the value 'example'

I tried to make an equivalent of socket.myvariable with session['myvariable']

@app.route("/a")
def helljo():
return render_template('index.html')

@socketio.on('connect')
def handleMessagae():
session['keyo'] = request.args.get('session') # /a?session=example
emit('connected', session.get('keyo'))

@socketio.on('message')
def handleMessage(message):
emit('message', {'pseudo':session.get('keyo'),'message':message} , broadcast=True, include_self=False)

Answer Source

The correct way to do what you want is:

@app.route("/a")
def helljo():
    session['keyo'] = request.args.get('session') # /a?session=example
    return render_template('index.html')

@socketio.on('connect')
def handleMessagae():
    emit('connected', session.get('keyo'))

@socketio.on('message')
def handleMessage(message):
    emit('message', {'pseudo':session.get('keyo'),'message':message} , broadcast=True, include_self=False)

The problem is that you are mixing up the HTTP request with the Socket.IO requests. If you invoke the /a endpoint with some query string args, you can only access those arguments in the handler for that endpoint. But saving them in the session makes them accessible later by the Socket.IO event handlers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download