Search code examples
pythonflaskwebsocketflask-socketioflask-session

How do I access flask-websocket sessions from inside flask functions


As the title states I'm having issues with accessing flask-websocket sessions from the flask functions. I have realised they are different and probably stored differently and tried to solve this using the flask-session library to no avail.

I have made some boilerplate code illustrating my problem.

from flask import Flask, session,render_template,url_for,redirect
from flask_socketio import SocketIO,join_room
app = Flask(__name__)
boards = {}
socketio = SocketIO(app)
app.secret_key = "temporary"
@app.route('/')
def index():
    return render_template('wait.html')
@app.route('/dir')
def foo():
    if "name" in session:#fails here as session is <SecureCookieSession {}> instead of {'name' : 'craig}
        pass #just a filler
    else:
        return redirect(url_for("index"))#this line will cause to repetitively go back and forward from index to foo
@socketio.on('log')
def connection(request):
    if "name" not in session:
        join_room('waiting')#in my actual code the user waits for another person
        session['name'] = 'craig'
        socketio.emit('redirect', url_for('foo'),room= 'waiting')
    else:
        pass

if __name__ == '__main__':  
   socketio.run(app ,port=5000, debug=True)

and the html:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        Waiting...
        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
        <script>
        const socket = io();
        socket.emit("log", { data: "connection" });
        socket.on('redirect', (dest) => {
            window.location = dest;
        });
        </script>
    </body>
</html>

Solution

  • Turns out flask-session did have the solution, I was just using it wrong forgetting these two lines of code when I initially tried:

    Session(app)
    socketio = SocketIO(app, manage_session=False)# I did not have the manage_session
    

    I also used

    session.modified = True
    

    though I'm not sure it is strictly necessary

    Here is the updated server code:

    from flask import Flask, session, render_template, url_for, redirect
    from flask_socketio import SocketIO, join_room
    from flask_session import Session
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'temporary'
    app.config['SESSION_TYPE'] = 'filesystem'
    Session(app)
    socketio = SocketIO(app, manage_session=False)
    
    @app.route('/')
    def index():
        return render_template('wait.html')
    
    @app.route('/dir')
    def foo():
        if "name" in session:
            name = session['name']
            return f"Hello, {name}!"
        else:
            return redirect(url_for("index"))
    
    @socketio.on('log')
    def connection(request):
        print(session)
        if "name" not in session:
            join_room('waiting')
            session['name'] = 'craig'
            session.modified = True
            socketio.emit('redirect', url_for('foo'), room='waiting')
        else:
            session.clear()
    
    if __name__ == '__main__':  
       socketio.run(app, port=5200, debug=True)