CallmeEchoo
CallmeEchoo

Reputation: 1

Flask-Session not persisting session data with Flask-SocketIO

I am deploying a Flask app with gunicorn using Flask-Socketio and Flask-Session.

On the 'connect' event I want to store the clients session id server-side using Flask-Session to identify the client on future request. The problem is that the session object provided by Flask does not seem to persist the saved data. In the example below I save the clients session id on the 'connect' event with session['sid'] = request.sid and try to log it out on the 'disconnect' event using session.get('sid'). However this will not log out the saved session id but the default value. This is also true for http requests on Flask routes.

in server.server.py

from server.routes.socketio_routes import init_socketio_routes

def init_routes(app, socketio):
    init_app_routes(app, socketio)
    init_socketio_routes(socketio)

def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'secret_key'
    app.config['SESSION_TYPE'] = 'cachelib'
    app.config['SESSION_FILE_DIR'] = FileSystemCache(cache_dir='sessions')

    Session(app)
    socketio = SocketIO(app, manage_session=False)

    init_routes(app, socketio)
    return app, socketio

in server.routs.socketio_routes.py

def init_socketio_routes(socketio: SocketIO):
    @socketio.on('connect')
    def handle_connect():
        session['sid'] = request.sid
        print(f"Session ID: {session.get('sid')} connected")

    @socketio.on('disconnect')
    def handle_disconnect():
        sid = session.get('sid')
        print(f"Session ID: {sid} disconnected")

in app.py

from server.server import create_app

app, socketio = create_app()

the output:

Session ID: AGDnl9e1mTkki6XAAAAB connected
server=127.0.0.1:8000//socket.io/ client=127.0.0.1:46222 socket shutdown error: [Errno 9] Bad file descriptor
Session ID: None disconnected

I use the following script launch.sh to start the server:

#!/bin/bash
#This script launches the Server.

if ! source .venv/bin/activate ; then exit 1 ; fi
gunicorn -w 1 -k eventlet app:app
exit $?

relevant file structure:

├── server/
│   ├── routes/
│   │   ├── app_routes.py
│   │   └── socketio_routes.py
│   └── server.py
│
├── .gitignore
├── README.md
├── app.py
├── launch.sh
├── requirements.txt

What I already tried:

Session(app)
CORS(app)
socketio = SocketIO(app, manage_session=False)

Upvotes: 0

Views: 39

Answers (0)

Related Questions