pythoneventsbrowserwebsocketrabbitmq

Easiest way to push RabbitMQ events to browser using WebSockets in Python?


I have an existing Python system that receives messages using Rabbit MQ. What is the absolute easiest way to get these events pushed to a browser using WebSockets using Python? Bonus if the solution works in all major browsers too.

Thanks, Virgil


Solution

  • Here https://github.com/Gsantomaggio/rabbitmqexample I wrote an complete example that uses tornado and RabbitMQ.

    You can find all the instruction from the site:

    anyway ..you need:

    pip install pika 
    pip install tornado 
    

    First you register your 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()
    

    then you register your web-sockets clients:

    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)
    

    When you get a message, you can redirect it to the web-socket page.

    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)