使用Python中的WebSockets将RabbitMQ事件推送到浏览器的最简单方法?

时间:2014-09-03 02:57:00

标签: python events browser websocket rabbitmq

我有一个使用Rabbit MQ接收消息的现有Python系统。使用Python使用WebSockets将这些事件推送到浏览器的绝对最简单的方法是什么?如果解决方案也适用于所有主流浏览器,则可获得奖励。

谢谢, 维吉尔

2 个答案:

答案 0 :(得分:5)

这里https://github.com/Gsantomaggio/rabbitmqexample我写了一个使用tornado和RabbitMQ的完整示例。

您可以从网站上找到所有说明:

无论如何..你需要:

pip install pika 
pip install tornado 

首先注册你的rabbitmq:

def threaded_rmq():
    channel.queue_declare(queue="my_queue")
    logging.info('consumer ready, on my_queue')
    channel.basic_consume(consumer_callback, queue="my_queue", no_ack=True) 
    channel.start_consuming()

然后注册您的网络套接字客户端:

class SocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        logging.info('WebSocket opened')
        clients.append(self)

    def on_close(self):
        logging.info('WebSocket closed')
        clients.remove(self)

收到消息后,您可以将其重定向到Web套接字页面。

def consumer_callback(ch, method, properties, body):
        logging.info("[x] Received %r" % (body,))
        # The messagge is brodcast to the connected clients
        for itm in clients:
            itm.write_message(body)

答案 1 :(得分:2)

您可以在服务器上使用TwistedtxAMQPAutobahn|Python在大约50行代码中编写桥接,并在浏览器端编写Autobahn|JS。 Autobahn实现了WebSocket,并且WAMP位于顶部,为您提供了Publish& amp;通过WebSocket订阅(以及远程过程调用)。

使用原始WebSocket时,您必须创建自己的Publish&通过WebSocket订阅 - 因为我猜你就是这样:将AMQP PubSub扩展到Web。或者你可以查看STOMP。

免责声明:我是WAMP和Autobahn的原作者。