Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments to Tornado's WebSocketHandler class?

Tags:

python

tornado

I am trying to pass an instance of my_object as an argument when initializing a WebSocketHandler instance in Tornado, so I can use it during the communication. I've tried to do the following but with no success.

class WSWebHandler(tornado.websocket.WebSocketHandler):
    def __init__(self, my_object):
        super(tornado.websocket.WebSocketHandler, self).__init__()
        self.my_object = my_object

    def open(self):
        print('new connection')

    def on_message(self, message):
        print('message received: %s' % message)

    def on_close(self):
        print('connection closed')

    def check_origin(self, origin):
        return True

my_object = new My_Object()

application = tornado.web.Application([(r'/ws', WSWebHandler), my_object])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8080)
myIP = socket.gethostbyname(socket.gethostname())
print ('*** Websocket Server Started at %s***' % myIP)
tornado.ioloop.IOLoop.instance().start()

Any guess of where I am mistaken?

Thanks in advance

like image 361
Leafar Avatar asked Apr 03 '18 10:04

Leafar


1 Answers

1. Passing local arguments

Tornado provides a different mechanism to pass arguments to a handler. Create a method called initialize in your handler class. Tornado will automatically call this method with your custom arguments:

class WSWebHandler(tornado.websocket.WebSocketHandler):
    def initialize(self, my_object):
        self.my_object = my_object

You're also passing the argument incorrectly. The correct way is this:

tornado.web.Application(
    [
        (r'/ws', WSWebHandler, {'my_object': my_object}),
       # \____/  \__________/  \______________________/
       #   url      handler       dict of extra args

    ],
)

2. Passing parameters from the URL

The above code is for passing local arguments. You can also pass dynamic parameters from the URL to the websocket handler like this:

tornado.web.Application(
    [
        (r'/ws/(?P<id>[0-9])', WSWebHandler),
    ],
)

# Now the websocket handler's `open` method will accept 
# a parameter called `id`
class WSWebHandler(tornado.websocket.WebSocketHandler):
    def open(self, id):
        # do something with id
        pass
like image 88
xyres Avatar answered Oct 23 '22 23:10

xyres