我正在尝试在Tornado中初始化my_object
实例时传递WebSocketHandler
的实例作为参数,因此我可以在通信期间使用它。我试图做以下但没有成功。
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()
我猜错了哪里?
提前致谢
答案 0 :(得分:7)
Tornado提供了一种将参数传递给处理程序的不同机制。在处理程序类中创建一个名为initialize
的方法。 Tornado将使用您的自定义参数自动调用此方法:
class WSWebHandler(tornado.websocket.WebSocketHandler):
def initialize(self, my_object):
self.my_object = my_object
您也错误地传递了参数。正确的方法是:
tornado.web.Application(
[
(r'/ws', WSWebHandler, {'my_object': my_object}),
# \____/ \__________/ \______________________/
# url handler dict of extra args
],
)