Nishant Singh
Nishant Singh

Reputation: 3199

Unable to retrieve Messages from AWS SQS queue using Boto

My python code looks like :

import json
import boto.sqs
import boto
from boto.sqs.connection import SQSConnection
from boto.sqs.message import Message
from boto.sqs.message import RawMessage


sqs = boto.connect_sqs(aws_access_key_id='XXXXXXXXXXXXXXX',aws_secret_access_key='XXXXXXXXXXXXXXXXX')
q = sqs.create_queue("Nishantqueue")  // Already present


q.set_message_class(RawMessage)
results = q.get_messages()
ret = "Got %s result(s) this time.\n\n" % len(results)

for result in results:
        msg = json.loads(result.get_body())
        ret += "Message: %s\n" % msg['message']

ret += "\n... done."
print ret

My SQS queue contains atleast 5 to 6 messages... when i execute this ... i get output as this and this is on every run, this code isn't able to pull the mssgs from the queue :

Got 0 result(s) this time.

...done.

I am sure i am missing something in the loop.... couldn't find though

Upvotes: 0

Views: 1651

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 269081

Your code is retrieving messages from an Amazon SQS queue, but it doesn't seem to be deleting them. This means that messages will be invisible for a period of time (specified by the visibility_timeout parameter), after which they will reappear. The expectation is that if a message is not deleted within this time, then it has failed to be processed and should reappear on the queue to try again.

Here's some code that pulls a message from a queue, then deletes it after processing. Note the visibility_timeout specified when a message is retrieved. It is using read() to simply return one message:

#!/usr/bin/python27

import boto, boto.sqs
from boto.sqs.message import Message

# Connect to Queue
q_conn = boto.sqs.connect_to_region("ap-southeast-2")
q = q_conn.get_queue('queue-name')

# Get a message
m = q.read(visibility_timeout=15)
if m == None:
  print "No message!"
else:
  print m.get_body()
  q.delete_message(m)

It's possible that your messages were invisible ("in-flight") when you tried to retrieve them.

Upvotes: 1

Related Questions