Last active
September 18, 2019 11:45
-
-
Save philschmid/176397a8ab9f0332c77ff08a5499c9f9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
def get_messages_from_queue(queue_url): | |
"""Generates messages from an SQS queue. | |
Note: this continues to generate messages until the queue is empty. | |
Every message on the queue will be deleted. | |
:param queue_url: URL of the SQS queue to drain. | |
""" | |
sqs_client = boto3.client('sqs') | |
while True: | |
resp = sqs_client.receive_message( | |
QueueUrl=queue_url, | |
AttributeNames=['All'], | |
MaxNumberOfMessages=10 | |
) | |
try: | |
yield from resp['Messages'] | |
except KeyError: | |
return | |
entries = [ | |
{'Id': msg['MessageId'], 'ReceiptHandle': msg['ReceiptHandle']} | |
for msg in resp['Messages'] | |
] | |
resp = sqs_client.delete_message_batch( | |
QueueUrl=queue_url, Entries=entries | |
) | |
if len(resp['Successful']) != len(entries): | |
raise RuntimeError( | |
f"Failed to delete messages: entries={entries!r} resp={resp!r}" | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
# Create SQS client | |
sqs = boto3.client('sqs') | |
queue_url = 'SQS_QUEUE_URL' | |
# Long poll for message on provided SQS queue | |
response = sqs.receive_message( | |
QueueUrl=queue_url, | |
AttributeNames=[ | |
'SentTimestamp' | |
], | |
MaxNumberOfMessages=1, | |
MessageAttributeNames=[ | |
'All' | |
], | |
WaitTimeSeconds=20 | |
) | |
print(response) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
sqs = boto3.client('sqs', region_name="us-west-2", | |
aws_access_key_id='', | |
aws_secret_access_key='' | |
) | |
queue_url = '' | |
response = sqs.receive_message( | |
QueueUrl=queue_url, | |
AttributeNames=[ | |
'SentTimestamp' | |
], | |
MaxNumberOfMessages=1, | |
MessageAttributeNames=[ | |
'All' | |
], | |
VisibilityTimeout=0, | |
WaitTimeSeconds=0 | |
) | |
try: | |
message = response['Messages'][0] | |
receipt_handle = message['ReceiptHandle'] | |
except KeyError: | |
print('No messages on the queue!') | |
messages = [] | |
sqs.delete_message( | |
QueueUrl=queue_url, | |
ReceiptHandle=receipt_handle | |
) | |
print('Received and deleted message: %s' % message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment