简体   繁体   中英

Share a value across Tornado Websockets server

I have a basic websocket server using Tornado framework in python. I want to share a value between the server functions:

class EchoWebSocket(websocket.WebSocketHandler):

    def check_origin(self, origin):
        return True
    def open(self):
        print ("connection opened")
    def on_close(self):
        tornado.ioloop.IOLoop.instance().stop()
        print ("connection closed")
    def on_message(self,message):
        print (message)

def Main():
    application = tornado.web.Application([(r"/", EchoWebSocket),])
    application.listen(9000)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    Main() 

I tried to create a global object from a class like this:

class operate:
    state = "mutual"

    def __init__(self):
        self.state = 'mutual'

    def play(self):
        self.state = 'play'

    def pause(self):
        self.state = 'pause'

    def getStatus(self):
        return self.state 

and call a global object, guessing that since the object is global it will be the same not creating a new one every message:

def open(self):
    global objectTV
    objectTV = operate()
    objectTV.play()
.
.
.
.
 def on_message(self,message):
        global objectTV
        objectTV = operate()
        print(objectTV.getStatus())

But it always print 'mutual'?

In the method on_message() , every time a new message arrives, you're instantiating objectTV again and again at objectTv = operate() . The new instance of operate class has the initial state set to 'mutual' , that is why it's printing 'mutual' .

A simple fix would be to remove objectTV = operate() line from on_message() and it should work like you want it to.

But read some answers on this question: Why are global variables evil? .

So, the better approach to solve your problem would be to set a local attribute on the handler instance instead:

class EchoWebSocket(websocket.WebSocketHandler):
    ...
    def open(self):
        self.objectTV = operate()
        self.objectTV.play()

    def on_message(self, message):
        print(self.objectTV.getStatus()) # -> 'play'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM