Search code examples
python-3.xtornadopython-packaging

Python Tornado extract handler for websockets


this python 3 code works as it is.

import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop

class WebSocketHandler(tornado.websocket.WebSocketHandler):
    connections = set()

    def open(self):
            self.connections.add(self)
            print ('new connection was opened')
            pass

    def on_message(self, message):
            print ('from WebSocket: ', message)
            messageTooSockets.put(message)

    def on_close(self):
            self.connections.remove(self)
            print ('connection closed')
            pass

class IndexPageHandler(tornado.web.RequestHandler):
    def get(self):
    self.render("index.html")

class webApplication(tornado.web.Application):
    def __init__(self):
    handlers = [
        (r'/', IndexPageHandler),
        (r'/websocket', WebSocketHandler),
        (r'/(.*)', tornado.web.StaticFileHandler, {'path': './root'})
    ]

    settings = {
        'template_path': 'templates'
    }
    tornado.web.Application.__init__(self, handlers, **settings)

if __name__ == '__main__':
    ws_app = webApplication()
    server = tornado.httpserver.HTTPServer(ws_app)
    server.listen(9090)
    tornado.ioloop.IOLoop.instance().start()

Extracting handlers was not a problem for request or static file handlers. However when extracting the websockets handler to a package in a subfolder tornado complains.

ERROR:tornado.application:Uncaught exception
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/tornado/http1connection.py", 
line 238, in _read_message
    delegate.finish()
  File "/usr/lib/python3/dist-packages/tornado/routing.py", line 251, 
in finish
    self.delegate.finish()
  File "/usr/lib/python3/dist-packages/tornado/web.py", line 2097, in 
finish
    self.execute()
  File "/usr/lib/python3/dist-packages/tornado/web.py", line 2117, in 
execute
    **self.handler_kwargs)
TypeError: __init__() takes 1 positional argument but 3 were given

Is there any specialty about tornado sockets when importing a tornado.websocket.WebSocketHandler handler ?


Solution

  • messageTooSockets was wrongly formatted...silly thought