Search code examples
websocketcelerytornado

send data from celery to tornado websocket


I have some periodic tasks which I execute with Celery (parse pages). Also I established a websocket with tornado.

I want to pass data from periodic tasks to tornado, then write this data to websocket and use this data on my html page.

How can I do this?

I tried to import module with tornado websocket from my module with celery tasks, but ofcourse, that didn't work.

I know only how to return some data, if I get a message from my client-side. Here is how I cope with it:

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import socket
'''
This is a simple Websocket Echo server that uses the Tornado websocket handler.
Please run `pip install tornado` with python of version 2.7.9 or greater to install tornado.
This program will echo back the reverse of whatever it recieves.
Messages are output to the terminal for debuggin purposes. 
''' 
class handler():
    wss = []



class WSHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print ('new connection')
        if self not in handler.wss:
            handler.wss.append(self)

    def on_message(self, message):
        print ('message received: ' + message)
        wssend('Ihaaaa')

    def on_close(self):
        print ('connection closed')
        if self in handler.wss:
            handler.wss.remove(self)

    def check_origin(self, origin):
        return True


def wssend(message):
    print(handler.wss)
    for ws in handler.wss:
        if not ws.ws_connection.stream.socket:
            print ("Web socket does not exist anymore!!!")
            handler.wss.remove(ws)
        else:
            print('I am trying!')
            ws.write_message(message)
            print('tried')

application = tornado.web.Application([
    (r'/ws', WSHandler),
])


if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    myIP = socket.gethostbyname(socket.gethostname())
    print ('*** Websocket Server Started at %s***' % myIP)
    main_loop = tornado.ioloop.IOLoop.instance()
    main_loop.start()

Solution

  • The option is to make a handle in tornado and then post results of celery task to this handle. After that, there will be an opportunity to pass this data to websocket.