Reputation: 11
I'm developing a Flask web application and using flask-sock for WebSocket communication. I need to pass WebSocket data received in send_output_with_context into filtered_chat_memory inside the index route.
Currently, I'm storing WebSocket output in a global list (terminal_output), but this creates a problem: if multiple users use the WebSocket simultaneously, their data gets mixed up. Since flask-sock does not have a manage_session parameter like flask-socketio, I'm struggling to isolate WebSocket data per user.
Here’s a simplified version of my code:
terminal_output = [] # Currently using a global variable
def send_output_with_context(channel, ws):
"""Handles WebSocket communication and stores output per user"""
while True:
if channel.recv_ready():
output = channel.recv(1024).decode('utf-8', errors='ignore')
try:
ws.send(output) # Send output to the WebSocket client
terminal_output.append({'role': 'assistant', 'content': output})
except:
break
@sock.route('/ws/ssh')
def ssh_websocket(ws):
"""WebSocket endpoint for SSH connection"""
while True:
data = ws.receive()
if data:
send_output_with_context(channel, ws)
@main_bp.route("/", methods=['POST'])
@login_required
def index():
"""Main route where I want to access WebSocket data"""
filtered_chat_memory = terminal_output + [msg for msg in chat_memory.get_history()]
return jsonify({'filtered_chat_memory': filtered_chat_memory})
Problem:
Currently, WebSocket data is stored in a global variable (terminal_output), leading to data leakage between users when multiple sessions are active. flask-sock does not provide a built-in way to manage session data like flask-socketio. Question: What is the best way to store WebSocket data per user in a Flask app using flask-sock?
I tried to change the library from flask-sock to flask-socketio, but I have to change alot of codes, so I prefer using flask-sock.
Upvotes: 1
Views: 24
Reputation: 67492
You are incorrect when you say that Flask-SocketIO handles this better than Flask-Sock. Both have the same limitations with regards to user sessions.
You are using Flask's native sessions, which are based on cookies. When you change the session in the WebSocket route, there is no way to update the session cookie, so changes that you make in the WS route will not be recorded on the session that is seen by HTTP routes. This is a limitation of the WebSocket protocol, which does not provide a mechanism to update cookies.
If you want the session to be shared across WS and HTTP routes, then use a server-side session solution such as Flask-Session. This should work both with Flask-Sock and Flask-SocketIO.
Upvotes: 0