Encapsulates Amazon SNS FIFO topic and subscription functions.
| 20 | |
| 21 | # snippet-start:[python.example_code.sns.FifoTopicWrapper] |
| 22 | class FifoTopicWrapper: |
| 23 | """Encapsulates Amazon SNS FIFO topic and subscription functions.""" |
| 24 | |
| 25 | def __init__(self, sns_resource): |
| 26 | """ |
| 27 | :param sns_resource: A Boto3 Amazon SNS resource. |
| 28 | """ |
| 29 | self.sns_resource = sns_resource |
| 30 | |
| 31 | # snippet-start:[python.example_code.sns.CreateFifoTopic] |
| 32 | def create_fifo_topic(self, topic_name): |
| 33 | """ |
| 34 | Create a FIFO topic. |
| 35 | Topic names must be made up of only uppercase and lowercase ASCII letters, |
| 36 | numbers, underscores, and hyphens, and must be between 1 and 256 characters long. |
| 37 | For a FIFO topic, the name must end with the .fifo suffix. |
| 38 | |
| 39 | :param topic_name: The name for the topic. |
| 40 | :return: The new topic. |
| 41 | """ |
| 42 | try: |
| 43 | topic = self.sns_resource.create_topic( |
| 44 | Name=topic_name, |
| 45 | Attributes={ |
| 46 | "FifoTopic": str(True), |
| 47 | "ContentBasedDeduplication": str(False), |
| 48 | "FifoThroughputScope": "MessageGroup", |
| 49 | }, |
| 50 | ) |
| 51 | logger.info("Created FIFO topic with name=%s.", topic_name) |
| 52 | return topic |
| 53 | except ClientError as error: |
| 54 | logger.exception("Couldn't create topic with name=%s!", topic_name) |
| 55 | raise error |
| 56 | |
| 57 | # snippet-end:[python.example_code.sns.CreateFifoTopic] |
| 58 | |
| 59 | # snippet-start:[python.example_code.sns.AddTopicPolicy] |
| 60 | @staticmethod |
| 61 | def add_access_policy(queue, topic_arn): |
| 62 | """ |
| 63 | Add the necessary access policy to a queue, so |
| 64 | it can receive messages from a topic. |
| 65 | |
| 66 | :param queue: The queue resource. |
| 67 | :param topic_arn: The ARN of the topic. |
| 68 | :return: None. |
| 69 | """ |
| 70 | try: |
| 71 | queue.set_attributes( |
| 72 | Attributes={ |
| 73 | "Policy": json.dumps( |
| 74 | { |
| 75 | "Version": "2012-10-17", |
| 76 | "Statement": [ |
| 77 | { |
| 78 | "Sid": "test-sid", |
| 79 | "Effect": "Allow", |
no outgoing calls