Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to modify a flask session inside a flask-socketio event?

I tried the following:

@socketio.on("signup req")
def signup_req(json):
    print(f"Response! {json}")
    socketio.emit("signup res", "RECEIVED!")
    session["user"] = {"name": json["name"]}

but when I want to access it by doing:

@app.route('/')
def index():
    ...
    print(session["user"])
    ...

I'll get a KeyError which means that the key didn't get stored inside the session.

like image 232
The Rainbow Avatar asked Jan 01 '23 01:01

The Rainbow


1 Answers

I wrote a blog post and video on this topic a while ago, because it is tricky. Here is the post: https://blog.miguelgrinberg.com/post/flask-socketio-and-the-user-session.

The short story is that cookie based sessions cannot be modified from a Socket.IO handler, simply because there is no way to set cookies over WebSocket. If you switch to a server-side session extension such as Flask-Session, then changes you make in your Socket.IO handlers do not need a cookie to be set in the client, so in that case the changes are saved and accessible from HTTP routes.

like image 179
Miguel Avatar answered Jan 03 '23 13:01

Miguel