Reputation: 127
Is there a way to give multiple socket handlers access to the same variable? Below is a bit of pseudo code showing what I'd like to achieve, but I'm getting an UnboundLocalVariable exception for shared_variable
.
shared_variable = None
@socketio.on('initialize')
def initialize_variable(data):
shared_variable = data
@socketio.on('print')
def print_variable():
print str(shared_variable)
Any thoughts? Thanks in advance!
Upvotes: 1
Views: 3070
Reputation: 67547
If you want to use a global variable, you have to declare it as such in the functions, or else each function will have its own local variable.
shared_variable = None
@socketio.on('initialize')
def initialize_variable(data):
global shared_variable
shared_variable = data
@socketio.on('print')
def print_variable():
global shared_variable
print str(shared_variable)
But note that if you do this, all your clients will share the same variable. A more interesting solution is to use the user session to store your values, because then each client will have its own values.
@socketio.on('initialize')
def initialize_variable(data):
session['shared_variable'] = data
@socketio.on('print')
def print_variable():
print str(session['shared_variable'])
It's important to note that there are a few differences in how session
behaves in Socket.IO events vs. regular HTTP request routes. The HTTP user session is copied over to the Socket.IO side when the client connects, and from then on any changes you make in Socket.IO events are only available to the events triggered by that client. Changes made to the session in Socket.IO events are not visible in HTTP requests.
Upvotes: 3