[Python] Flask-Session not persisting session data with Flask-SocketIO

Discussão em 'Python' iniciado por Stack, Dezembro 18, 2024.

  1. Stack

    Stack Membro Participativo

    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.

    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


    @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")


    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 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 $?

    What I already tried:

    • I tried to use different worker like gevent.
    • I tried using flask-cors by adding:

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

    • I tried using manage_session=True but this leads to http requests not being able to access the session data
    • I tried using different session types like filesystem
    • I tried clearing caches, cookies and local session files
    • I tried using session.modified = True after session['sid'] = request.sid

    Continue reading...

Compartilhe esta Página