How to share variables between socket handlers?

99封情书 提交于 2019-12-12 03:44:45

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/37443268/how-to-share-variables-between-socket-handlers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!