Search code examples
python-3.xdataframerabbitmqpikapython-pika

Getting 'positional argument' Error while sending a XML file to RabbitMQ from Python


I am trying to send a XML file to RabbitMQ from python but I am getting the below error

Error

File "<ipython-input-134-8a1b7f8b2e41>", line 3
    channel.basic_publish(exchange='',queue='abc',''.join(lines))
                                                                 ^
SyntaxError: positional argument follows keyword argument

My Code

import ssl
!pip install pika
import pika
ssl_options = pika.SSLOptions(ssl._create_unverified_context())
credentials = pika.PlainCredentials(username='abcc', password='abcc')
connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='xxxx', port=5671, virtual_host ='xxx', credentials=credentials, 
        ssl_options=ssl_options))
channel = connection.channel()
result = channel.queue_declare(queue='abc')
with open('20200205280673.xml', 'r') as fp:
    lines = fp.readlines()
channel.basic_publish(exchange='',queue='abc',''.join(lines))

Whats wrong in the above code?


Solution

  • As @ymz suggested, you are missing the body key in the basic.publish method. Also, the basic_publish method has no argument called queue. Please have a look at its implementation docs

    Edit #1: I have already answered this question elsewhere How to send a XML file to RabbitMQ using Python?

    Edit #2: Automating publishing of XML files. Assuming all the files are present in a directory called xml_files

    import os
    
    DIR = '/path/to/xml_files'
    
    for filename in os.listdir(DIR):
        filepath = f"{DIR}/{filename}"
        with open(filepath) as fp:
            lines = fp.readlines()
        channel.basic_publish(exchange='exchange', routing_key='queue', body=''.join(lines))