Skip to content

Instantly share code, notes, and snippets.

@snay2
Created March 3, 2011 22:21
Show Gist options
  • Save snay2/853743 to your computer and use it in GitHub Desktop.
Save snay2/853743 to your computer and use it in GitHub Desktop.
Examples using SQS
import uuid
import time
import boto
import json
from boto.sqs.message import RawMessage
AWSKey = "{redacted}"
AWSSecret = "{redacted}"
testQueue = "testqueue"
# Pushes a message onto the queue
def addMessageToQueue(message):
# Data required by the API
data = {
'submitdate': time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()),
'key': str(uuid.uuid1()),
'message': str(message)
}
# Connect to SQS and open the queue
sqs = boto.connect_sqs(AWSKey, AWSSecret)
q = sqs.create_queue(testQueue)
# Put the message in the queue
m = RawMessage()
m.set_body(json.dumps(data))
status = q.write(m)
# Polls the queue for messages
def readMessageFromQueue():
# Open the queue
sqs = boto.connect_sqs(AWSKey, AWSSecret)
q = sqs.create_queue(testQueue)
q.set_message_class(RawMessage)
# Get all the messages in the queue
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."
return ret
<form action="sendMessage" method="POST">
<p>Enter your message here:
<textarea name="message"></textarea></p>
<p><input type="submit" value="Send message" /></p>
</form>
<p><a href="readMessage">Wait for a message in the queue</a></p>
import funcs
from Cheetah.Template import Template
def index(req):
t = Template(file='/var/www/html/examples/sqs/index.html')
req.content_type = 'text/html'
return t.__str__()
def sendMessage(req):
message = req.form.getfirst('message')
funcs.addMessageToQueue(message)
return "Done."
def readMessage(req):
return funcs.readMessageFromQueue()
@gangtao
Copy link

gangtao commented Jun 26, 2014

It is great!
on line:34, is get_queue() better than create_queue() ?

@sackville
Copy link

From the SQS Boto docs for create_queue():

Calling this method on an existing queue name will not return an error from SQS unless the value for visibility_timeout is different than the value of the existing queue of that name. This is still an expensive operation, though, and not the preferred way to check for the existence of a queue. See the boto.sqs.connection.SQSConnection.lookup() method.

So I think the answer is yes, gangtao: get_queue() or lookup() would be better. A little more code would likely be necessary, but the results would still be better.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment