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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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
</code>
<code>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 </code>
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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")
</code>
<code>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") </code>
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from server.server import create_app
app, socketio = create_app()
</code>
<code>from server.server import create_app app, socketio = create_app() </code>
from server.server import create_app

app, socketio = create_app()

the output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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
</code>
<code>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 </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>#!/bin/bash
#This script launches the Server.
if ! source .venv/bin/activate ; then exit 1 ; fi
gunicorn -w 1 -k eventlet app:app
exit $?
</code>
<code>#!/bin/bash #This script launches the Server. if ! source .venv/bin/activate ; then exit 1 ; fi gunicorn -w 1 -k eventlet app:app exit $? </code>
#!/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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>├── server/
│ ├── routes/
│ │ ├── app_routes.py
│ │ └── socketio_routes.py
│ └── server.py
├── .gitignore
├── README.md
├── app.py
├── launch.sh
├── requirements.txt
</code>
<code>├── server/ │ ├── routes/ │ │ ├── app_routes.py │ │ └── socketio_routes.py │ └── server.py │ ├── .gitignore ├── README.md ├── app.py ├── launch.sh ├── requirements.txt </code>
├── server/
│   ├── routes/
│   │   ├── app_routes.py
│   │   └── socketio_routes.py
│   └── server.py
│
├── .gitignore
├── README.md
├── app.py
├── launch.sh
├── requirements.txt

What I already tried:

  • I tried to use different worker like gevent.
  • I tried using flask-cors by adding:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Session(app)
CORS(app)
socketio = SocketIO(app, manage_session=False)
</code>
<code>Session(app) CORS(app) socketio = SocketIO(app, manage_session=False) </code>
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

New contributor

CallmeEchoo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật