当仅实例化两个类时,如何在两个类之间共享变量?

时间:2019-02-18 15:49:08

标签: python tornado

所以我有2个python文件,main.py是主文件,web.py包含Web应用程序代码(使用Tornado)。因此,在web.py中,我想在主Web应用程序类(在main.py中实例化的WebAppModule)和另一个类(WSHandler,从客户端处理WebSocket连接)之间共享变量。但是,我唯一想到的方法是使用全局变量(如下面通过 is_button_clicked 变量演示的那样)。还有其他方法吗?

main.py

from web import WebAppModule

web_client = WebAppModule(9000)  

web.py

clients = []
wsThread = None
is_button_clicked = None

class WebAppModule():
    def __init__(self,portnumber):
        global is_button_clicked
        is_button_clicked = False
        self.process_running = ""
        self.connection_open = False

    def some_other_function:
        pass


class MyStaticFileHandler(tornado.web.StaticFileHandler):
    def set_extra_headers(self, path):
        self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('web/index.html')


class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        if len(clients)==0:
            clients.append(self)
            print 'web app connection opened...'
        else:
            print 'Another client already accessed the UI. Connection blocked...'

    def check_origin(self, origin):
        return True

    def on_message(self, message):
        for client in clients:    
            if "BUTTON_CLICKED" in message:
                global is_button_clicked
                is_button_clicked = True

    def on_close(self):
        try:
            clients.remove(self)
            print 'connection closed...'
        except Exception, e:
            print "Client not established. Skipped..."


settings = {
    "static_path": os.path.join(os.path.dirname(__file__), "web"),
    "static_hash_cache": False,
}    

application = tornado.web.Application([
    (r'/ws', WSHandler),
    (r'/', MainHandler),
], static_path=os.path.join(os.path.dirname(__file__), "web"), static_handler_class=MyStaticFileHandler)

1 个答案:

答案 0 :(得分:0)

您需要使用可变对象。字符串是不可变的。原因是python仅评估一次,因此在运行期间整个应用程序都会更改任何可变的可变字符串。

shared = {'wsThread':None,
          'is_button_clicked':None
         }

然后以如下所示的def更新:

def set(self, value):
    shared['is_button_clicked'] = value

def get(self):
    return shared['is_button_clicked']