Search code examples
python-3.xpandasrabbitmqsendrabbitmq-exchange

How to send a XML file to RabbitMQ using Python?


I am having an xml file called Test.xml which I am trying to send RabbitMQ using python.

I know below deatails regarding the Rabbit MQ

Hostname: xxx.xxxx.xxx

AMQP Port (SSL)  :4589

ESB Portal (Message Search): http://xxx.xxx.xxx:8585

RabbitMQ Web UI (https) :https://xxx.xxx.xxxx:15672 

How can this be done from python?


Solution

  • This can be done using pika, you can read the file content and send it as a big string to RabbitMQ. And on the other side you can parse the content using ElementTree.fromstring.

    Connection details:

    credentials = pika.PlainCredentials('username', 'password')
    conn = pika.BlockingConnection(pika.ConnectionParameters('host', port, 'vhost', credentials))
    channel = conn.channel()
    

    Publisher:

    with open('filename.xml', 'r') as fp:
        lines = fp.readlines()
    channel.basic_publish('exchange', 'queue', ''.join(lines))
    

    Consumer:

    def on_message(unused_channel, unused_method_frame, unused_header_frame, body):
        lines = body.decode()
        doc = ElementTree.fromstring(lines)
        tags = doc.findall("tag")
    
        ## DO YOUR STUFF HERE
    
    channel.basic_consume('queue', on_message)
    channel.start_consuming()
    

    Hope this helps!

    RabbitMQ flow:

    RabbitMQ flow

    Reference: RabbitMQ docs