Skip to content

Instantly share code, notes, and snippets.

@shapiromatron
Last active June 21, 2019 14:20
Show Gist options
  • Select an option

  • Save shapiromatron/fbc3a0e752413bbf9e68523378ddbd34 to your computer and use it in GitHub Desktop.

Select an option

Save shapiromatron/fbc3a0e752413bbf9e68523378ddbd34 to your computer and use it in GitHub Desktop.
boto aws queue example
from datetime import datetime
import logging
import sys
import time
import click
import boto3
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
QUEUE_NAME = "example-queue"
def get_sqs_queue(queue_name: str):
sqs = boto3.resource("sqs")
return sqs.get_queue_by_name(QueueName=queue_name)
@click.group()
def cli():
pass
@cli.command()
def send():
queue = get_sqs_queue(QUEUE_NAME)
queue.set_attributes(Attributes={"ReceiveMessageWaitTimeSeconds": "20"})
try:
while True:
payload = f"Hello at {datetime.now()}"
click.echo(f'Sending: "{payload}"')
queue.send_message(MessageBody=payload)
time.sleep(1)
except KeyboardInterrupt:
click.echo("Shutting down...")
@cli.command()
def listen():
queue = get_sqs_queue(QUEUE_NAME)
try:
while True:
logging.info("Polling queue...")
for message in queue.receive_messages(
WaitTimeSeconds=5, MaxNumberOfMessages=10
):
click.echo(f'Received: "{message.body}"')
message.delete()
else:
pass
time.sleep(5)
except KeyboardInterrupt:
click.echo("Shutting down...")
if __name__ == "__main__":
cli()
# in one shell
python queue_example send
# in another shell
python queue_example receive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment