0

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.

Paula Cogeanu
  • 231
  • 1
  • 10

1 Answers1

0

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.

Ben Darnell
  • 21,844
  • 3
  • 29
  • 50
  • hi ! what is a shared object, can you please detail a little bit on how to do this ? A link to a source code or a code snippet would also help. thanks. – Paula Cogeanu Jan 13 '15 at 10:46
  • I just mean some object that you create at startup and store somewhere accessible to all instances. This could be as simple as a global variable, like the MessageBuffer in https://github.com/tornadoweb/tornado/blob/stable/demos/chat/chatdemo.py – Ben Darnell Jan 13 '15 at 13:52
  • You can put anything there; I'd generally recommend putting a callback object instead of the WSHandler itself (so you can support mixed websocket/long-polling use). The global variable would be a container for multiple handlers' callbacks. – Ben Darnell Jan 13 '15 at 20:49
  • Mix them how? This is getting to be too broad a topic for a comment thread. Tornado's demo directory has two separate versions of the chat demo, one for long polling and one for websockets, but it would be possible to combine the two. Just make sure that the MessageBuffer (or equivalent) deals in abstract callbacks instead of calling methods like write_message directly. – Ben Darnell Jan 14 '15 at 14:24
  • Yes, you can use a regular RequestHandler for client-to-server and websockets for server-to-client. – Ben Darnell Jan 14 '15 at 19:27