Reputation: 98
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.
Upvotes: 6
Views: 3366
Reputation: 67479
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.
Upvotes: 13