1
# Copyright (c) 2006-2009 Mitch Garnaat http://garnaat.org/
3
# Permission is hereby granted, free of charge, to any person obtaining a
4
# copy of this software and associated documentation files (the
5
# "Software"), to deal in the Software without restriction, including
6
# without limitation the rights to use, copy, modify, merge, publish, dis-
7
# tribute, sublicense, and/or sell copies of the Software, and to permit
8
# persons to whom the Software is furnished to do so, subject to the fol-
11
# The above copyright notice and this permission notice shall be included
12
# in all copies or substantial portions of the Software.
14
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
16
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
17
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23
Represents an SQS Queue
27
from boto.sqs.message import Message
32
def __init__(self, connection=None, url=None, message_class=Message):
33
self.connection = connection
35
self.message_class = message_class
36
self.visibility_timeout = None
40
val = urlparse.urlparse(self.url)[2]
48
val = urlparse.urlparse(self.url)[2].split('/')[2]
52
name = property(_name)
54
def startElement(self, name, attrs, connection):
57
def endElement(self, name, value, connection):
58
if name == 'QueueUrl':
60
elif name == 'VisibilityTimeout':
61
self.visibility_timeout = int(value)
63
setattr(self, name, value)
65
def set_message_class(self, message_class):
67
Set the message class that should be used when instantiating messages read
68
from the queue. By default, the class boto.sqs.message.Message is used but
69
this can be overriden with any class that behaves like a message.
71
:type message_class: Message-like class
72
:param message_class: The new Message class
74
self.message_class = message_class
76
def get_attributes(self, attributes='All'):
78
Retrieves attributes about this queue object and returns
79
them in an Attribute instance (subclass of a Dictionary).
81
:type attributes: string
82
:param attributes: String containing one of:
83
ApproximateNumberOfMessages,
84
ApproximateNumberOfMessagesNotVisible,
87
LastModifiedTimestamp,
89
:rtype: Attribute object
90
:return: An Attribute object which is a mapping type holding the
91
requested name/value pairs
93
return self.connection.get_queue_attributes(self, attributes)
95
def set_attribute(self, attribute, value):
97
Set a new value for an attribute of the Queue.
99
:type attribute: String
100
:param attribute: The name of the attribute you want to set. The
101
only valid value at this time is: VisibilityTimeout
103
:param value: The new value for the attribute.
104
For VisibilityTimeout the value must be an
105
integer number of seconds from 0 to 86400.
108
:return: True if successful, otherwise False.
110
return self.connection.set_queue_attribute(self, attribute, value)
112
def get_timeout(self):
114
Get the visibility timeout for the queue.
117
:return: The number of seconds as an integer.
119
a = self.get_attributes('VisibilityTimeout')
120
return int(a['VisibilityTimeout'])
122
def set_timeout(self, visibility_timeout):
124
Set the visibility timeout for the queue.
126
:type visibility_timeout: int
127
:param visibility_timeout: The desired timeout in seconds
129
retval = self.set_attribute('VisibilityTimeout', visibility_timeout)
131
self.visibility_timeout = visibility_timeout
134
def add_permission(self, label, aws_account_id, action_name):
136
Add a permission to a queue.
138
:type label: str or unicode
139
:param label: A unique identification of the permission you are setting.
140
Maximum of 80 characters ``[0-9a-zA-Z_-]``
141
Example, AliceSendMessage
143
:type aws_account_id: str or unicode
144
:param principal_id: The AWS account number of the principal who will be given
145
permission. The principal must have an AWS account, but
146
does not need to be signed up for Amazon SQS. For information
147
about locating the AWS account identification.
149
:type action_name: str or unicode
150
:param action_name: The action. Valid choices are:
151
\*|SendMessage|ReceiveMessage|DeleteMessage|
152
ChangeMessageVisibility|GetQueueAttributes
155
:return: True if successful, False otherwise.
158
return self.connection.add_permission(self, label, aws_account_id, action_name)
160
def remove_permission(self, label):
162
Remove a permission from a queue.
164
:type label: str or unicode
165
:param label: The unique label associated with the permission being removed.
168
:return: True if successful, False otherwise.
170
return self.connection.remove_permission(self, label)
172
def read(self, visibility_timeout=None):
174
Read a single message from the queue.
176
:type visibility_timeout: int
177
:param visibility_timeout: The timeout for this message in seconds
179
:rtype: :class:`boto.sqs.message.Message`
180
:return: A single message or None if queue is empty
182
rs = self.get_messages(1, visibility_timeout)
188
def write(self, message):
190
Add a single message to the queue.
192
:type message: Message
193
:param message: The message to be written to the queue
195
:rtype: :class:`boto.sqs.message.Message`
196
:return: The :class:`boto.sqs.message.Message` object that was written.
198
new_msg = self.connection.send_message(self, message.get_body_encoded())
199
message.id = new_msg.id
200
message.md5 = new_msg.md5
203
def new_message(self, body=''):
205
Create new message of appropriate class.
207
:type body: message body
208
:param body: The body of the newly created message (optional).
210
:rtype: :class:`boto.sqs.message.Message`
211
:return: A new Message object
213
m = self.message_class(self, body)
217
# get a variable number of messages, returns a list of messages
218
def get_messages(self, num_messages=1, visibility_timeout=None,
221
Get a variable number of messages.
223
:type num_messages: int
224
:param num_messages: The maximum number of messages to read from the queue.
226
:type visibility_timeout: int
227
:param visibility_timeout: The VisibilityTimeout for the messages read.
229
:type attributes: str
230
:param attributes: The name of additional attribute to return with response
231
or All if you want all attributes. The default is to
232
return no additional attributes. Valid values:
236
ApproximateReceiveCount
237
ApproximateFirstReceiveTimestamp
240
:return: A list of :class:`boto.sqs.message.Message` objects.
242
return self.connection.receive_message(self, number_messages=num_messages,
243
visibility_timeout=visibility_timeout,
244
attributes=attributes)
246
def delete_message(self, message):
248
Delete a message from the queue.
250
:type message: :class:`boto.sqs.message.Message`
251
:param message: The :class:`boto.sqs.message.Message` object to delete.
254
:return: True if successful, False otherwise
256
return self.connection.delete_message(self, message)
262
return self.connection.delete_queue(self)
264
def clear(self, page_size=10, vtimeout=10):
265
"""Utility function to remove all messages from a queue"""
267
l = self.get_messages(page_size, vtimeout)
270
self.delete_message(m)
272
l = self.get_messages(page_size, vtimeout)
275
def count(self, page_size=10, vtimeout=10):
277
Utility function to count the number of messages in a queue.
278
Note: This function now calls GetQueueAttributes to obtain
279
an 'approximate' count of the number of messages in a queue.
281
a = self.get_attributes('ApproximateNumberOfMessages')
282
return int(a['ApproximateNumberOfMessages'])
284
def count_slow(self, page_size=10, vtimeout=10):
286
Deprecated. This is the old 'count' method that actually counts
287
the messages by reading them all. This gives an accurate count but
288
is very slow for queues with non-trivial number of messasges.
289
Instead, use get_attribute('ApproximateNumberOfMessages') to take
290
advantage of the new SQS capability. This is retained only for
294
l = self.get_messages(page_size, vtimeout)
298
l = self.get_messages(page_size, vtimeout)
301
def dump_(self, file_name, page_size=10, vtimeout=10, sep='\n'):
302
"""Utility function to dump the messages in a queue to a file
303
NOTE: Page size must be < 10 else SQS errors"""
304
fp = open(file_name, 'wb')
306
l = self.get_messages(page_size, vtimeout)
309
fp.write(m.get_body())
313
l = self.get_messages(page_size, vtimeout)
317
def save_to_file(self, fp, sep='\n'):
319
Read all messages from the queue and persist them to file-like object.
320
Messages are written to the file and the 'sep' string is written
321
in between messages. Messages are deleted from the queue after
322
being written to the file.
323
Returns the number of messages saved.
329
fp.write(m.get_body())
332
self.delete_message(m)
336
def save_to_filename(self, file_name, sep='\n'):
338
Read all messages from the queue and persist them to local file.
339
Messages are written to the file and the 'sep' string is written
340
in between messages. Messages are deleted from the queue after
341
being written to the file.
342
Returns the number of messages saved.
344
fp = open(file_name, 'wb')
345
n = self.save_to_file(fp, sep)
349
# for backwards compatibility
350
save = save_to_filename
352
def save_to_s3(self, bucket):
354
Read all messages from the queue and persist them to S3.
355
Messages are stored in the S3 bucket using a naming scheme of::
357
<queue_id>/<message_id>
359
Messages are deleted from the queue after being saved to S3.
360
Returns the number of messages saved.
366
key = bucket.new_key('%s/%s' % (self.id, m.id))
367
key.set_contents_from_string(m.get_body())
368
self.delete_message(m)
372
def load_from_s3(self, bucket, prefix=None):
374
Load messages previously saved to S3.
378
prefix = '%s/' % prefix
380
prefix = '%s/' % self.id[1:]
381
rs = bucket.list(prefix=prefix)
384
m = self.new_message(key.get_contents_as_string())
388
def load_from_file(self, fp, sep='\n'):
389
"""Utility function to load messages from a file-like object to a queue"""
395
m = Message(self, body)
398
print 'writing message %d' % n
405
def load_from_filename(self, file_name, sep='\n'):
406
"""Utility function to load messages from a local filename to a queue"""
407
fp = open(file_name, 'rb')
408
n = self.load_file_file(fp, sep)
412
# for backward compatibility
413
load = load_from_filename