【问题标题】:Setting and Getting Variables within an imported Class在导入的类中设置和获取变量
【发布时间】:2015-06-26 15:37:33
【问题描述】:

所有,我正在使用烧瓶/uWSGI 实现 websocket。这归结为在主应用程序中实例化的模块。服务器和模块的编辑代码:

ma​​in.py

from WSModule import WSModule
app = Flask(__name__)
wsmodule = WSModule()
websock = WebSocket(app)

@websock.route('/websocket')
def echo(ws):
    wsmodule.register(ws)
    print("websock clients", wsmodule.clients)    
    while True: # This while loop is related to the uWSGI websocket implementation
        msg = ws.receive()
        if msg is not None:
            ws.send(msg)
        else: return

@app.before_request
def before_request():
    print ("app clients:",wsmodule.clients)

WSModule.py

class WSModule(object):

    def __init__(self):
        self.clients = list()

    def register(self, client):
        self.clients.append(client) 

问题:当用户使用 websockets 连接时(进入 '/websocket' 路由),wsmodule.register 会附加他们的连接套接字,这可以正常工作 - 打印输出 'websocket clients' 显示附加的连接. 问题是我无法从主应用程序访问这些套接字。从永远不会更新的“应用程序客户端”打印输出中可以看到这一点(列表保持为空)。某些内容明显在更新,但如何访问这些更改?

【问题讨论】:

    标签: python-3.x flask


    【解决方案1】:

    听起来您的程序正在使用threadsprocesses 运行,并且每个正在运行的thread/process 都存在一个wsmodule

    因此,一个wsmodule 正在使用客户信息进行更新,而另一个客户正在询问客户信息……但所询问的那个仍然是空的。

    如果您使用的是threads,请查看thread local storage

    【讨论】:

    • 我使用 os.getpid() 验证确实有多个 wsmodule 实例。线程本地数据在这里有什么帮助?如果有多个进程正在运行,那么线程本地数据肯定不会有用;或者我完全没有抓住重点(+1 以解决问题)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多