Search code examples
python-3.xpandasloopspython-itertoolspika

How to loop records from a directory and pass into a MQ function in python?


I have set xmls in a directory XML.

123.xml
234.xml
567.xml

I want my code to loop into the directory and each xml and pass into the MQ.

Currently I am able to successfully sent 1 XML using current code.

I am not sure how automatically create incremanetal UUID for each XML in folder and how loop in the below code.

Current Working Code for harcorded XML value

import ssl
!pip install pika
import pika
import uuid


def send(message):

    uui = uuid.uuid4()
    mydoc = open('123.xml')
    xml = mydoc.read()    


    ssl_options = pika.SSLOptions(ssl._create_unverified_context())
    credentials = pika.PlainCredentials(username='xxxxx', password='xxxx')
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='xxxx', port=5671, virtual_host ='abcd' , 
                                        credentials=credentials, ssl_options=ssl_options))

    channel = connection.channel()
    channel.basic_publish(exchange='xxxxxx', routing_key='',properties=pika.BasicProperties(
                          headers={'uuid': str(uui)}), body=xml)
    connection.close()

    print(message + ' ' + str(uui))

    return message

How can do this in python?


Solution

  • You want the list of XMLs in the directory?

    Just read the directory and get the files in the directory, then loop through it to perform your action.

    import ssl
    !pip install pika
    import pika
    import uuid
    import os
    
    
    def send(message):
    
        xml_files = [file for file in os.listdir(path_to_your_directory) if os.path.isfile(os.path.join(path_to_your_directory, file)) and file.split('.')[-1] == 'xml']
        uui = uui = uuid.uuid4()
    
        for file in xml_file:
            mydoc = open(file)
            xml = mydoc.read()    
    
    
            ssl_options = pika.SSLOptions(ssl._create_unverified_context())
            credentials = pika.PlainCredentials(username='xxxxx', password='xxxx')
            connection = pika.BlockingConnection(pika.ConnectionParameters(host='xxxx', port=5671, virtual_host ='abcd' , 
                                            credentials=credentials, ssl_options=ssl_options))
    
            channel = connection.channel()
            channel.basic_publish(exchange='xxxxxx', routing_key='',properties=pika.BasicProperties(
                              headers={'uuid': str(uui)}), body=xml)
            connection.close()
            next_uui_hex = hex(int(str(uui).replace('-','').upper(),16) + 1)
            uui = uuid.UUID(next_uui_hex[2:11] + '-' + next_uui_hex[11:15] + '-' + next_uui_hex[15:19] + '-' + next_uui_hex[19:23] + '-' + next_uui_hex[23:])
    
            print(message + ' ' + str(uui))
    
        return message