Search code examples
botomessageamazon-sqs

boto.sqs: read and write SQS messages


I would like to read messages from one que and write them to another que. But, the message class is custom format and I am not sure how to write a message class and import it.

That is, the structure follows as:

import boto.sqs

#read messages from one que
conn = boto.sqs.connect_to_region("regionName")
q=conn.get_queue('queueName')
res=q.get_messages()
m = res[0].get_body() #This is the message I read 

#Now, I want to write the message into another que
r = conn.get_queue('DifferentqueueName')
r.write(m)

Here, the code breaks and I get the following error messages:

224         new_msg = self.connection.send_message(self,
--> 225             message.get_body_encoded(), delay_seconds=delay_seconds,
226             message_attributes=message.message_attributes)
227         message.id = new_msg.id

AttributeError: 'unicode' object has no attribute 'get_body_encoded'

How can define a custom message class and use it to write to another que? Or, if I could just inherit the class when reading messages and use it for writing, that would be even easier. Can I do any of these?

Thank you.


Solution

  • The reason you are getting the error is because you are attempting to write a raw string to the queue rather than a Message object. Try this, instead:

    import boto.sqs
    
    #read messages from one que
    conn = boto.sqs.connect_to_region("regionName")
    q1 = conn.get_queue('queueName')
    q2 = conn.get_queue('DifferentqueueName')
    messages = q1.get_messages()
    for message in messages:
        msg_body = message.get_body() #This is the message I read
        # Now, I want to write the message into another queue       
        new_msg = q2.new_message(msg_body)
        q2.write(new_msg)