从芹菜发送数据到龙卷风websocket

时间:2016-12-05 19:29:27

标签: websocket celery tornado

我有一些周期性的任务,我用Celery(解析页面)执行。 我还建立了一个带龙卷风的websocket。

我想将周期性任务中的数据传递给龙卷风,然后将这些数据写入websocket并在我的html页面上使用这些数据。

我该怎么做?

我试图用我的模块用芹菜任务导入带有龙卷风websocket的模块,但当然,这不起作用。

如果我从客户端收到消息,我只知道如何返回一些数据。以下是我应对的方法:

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()

1 个答案:

答案 0 :(得分:0)

选项是在龙卷风中制作一个句柄,然后将芹菜任务的结果发布到此句柄。 之后,将有机会将此数据传递给websocket。

相关问题