From 9be4da76c172dcbd2a9f012955116b2678aed869 Mon Sep 17 00:00:00 2001 From: Timo Zimmermann Date: Tue, 22 Sep 2020 15:58:06 +0200 Subject: [PATCH] try to get SQS queue before creating it In some environments permissions for an IAM role or access key might not include "SQS create". The broker should first try to get the queue and if this fails try to create it as fall back to the current default behaviour. --- django_q/brokers/aws_sqs.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/django_q/brokers/aws_sqs.py b/django_q/brokers/aws_sqs.py index 1a6deda9..1143b766 100644 --- a/django_q/brokers/aws_sqs.py +++ b/django_q/brokers/aws_sqs.py @@ -1,9 +1,13 @@ from boto3 import Session +from botocore.client import ClientError from django_q.brokers import Broker from django_q.conf import Conf +QUEUE_DOES_NOT_EXIST = "AWS.SimpleQueueService.NonExistentQueue" + + class Sqs(Broker): def __init__(self, list_key: str = Conf.PREFIX): self.sqs = None @@ -62,4 +66,13 @@ def get_connection(list_key: str = Conf.PREFIX) -> Session: def get_queue(self): self.sqs = self.connection.resource("sqs") + + try: + # try to return an existing queue by name. If the queue does not + # exist try to create it. + return self.sqs.get_queue_by_name(QueueName=self.list_key) + except ClientError as exp: + if not exp.response["Error"]["Code"] == QUEUE_DOES_NOT_EXIST: + raise exp + return self.sqs.create_queue(QueueName=self.list_key)