can a single instance of websocket[tornado] to handle different requests?

社会主义新天地 提交于 2019-12-25 04:45:33

问题


I work on a project which uses Ajax and Websockets. The task is to get rid of the Ajax and to use Websockets only. On the server side I'm using tornado and django with a tornado-url-dispatcher. I want to reuse some methods already defined in django using a single instance of websocket(tornado.websocket.WebSocketHandler). This class has 3 default handlers but I extended it by adding new handlers which redirects to the existent django methods and modified the dispatcher to point to the new methods.

class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        ...
    def on_message(self, message):
        ...
    def on_close(self):
        ...
    def new_handler_1(self, request):
        ...

tornado_app = tornado.web.Application(
    [
      (r'/ws/new_handler', wshandler.WSHandler.new_handler_1),
      (r'/ws', wshandler.WSHandler),
    ]

What type of response shall I use in order to reply from new_handler_1 method to a request done via a websocket ? Thanks.


回答1:


You can't do this; a new instance of the handler class is created for every request. Instead, make some other shared object that the handlers can use to communicate between themselves. You can pass this object to the handlers either by attaching it to the Application object or passing it as an initialize argument to the handler.



来源:https://stackoverflow.com/questions/27904180/can-a-single-instance-of-websockettornado-to-handle-different-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!