Encapsulates Amazon SNS topic and subscription functions.
| 20 | |
| 21 | # snippet-start:[python.example_code.sns.SnsWrapper] |
| 22 | class SnsWrapper: |
| 23 | """Encapsulates Amazon SNS 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-end:[python.example_code.sns.SnsWrapper] |
| 32 | |
| 33 | # snippet-start:[python.example_code.sns.CreateTopic] |
| 34 | def create_topic(self, name): |
| 35 | """ |
| 36 | Creates a notification topic. |
| 37 | |
| 38 | :param name: The name of the topic to create. |
| 39 | :return: The newly created topic. |
| 40 | """ |
| 41 | try: |
| 42 | topic = self.sns_resource.create_topic(Name=name) |
| 43 | logger.info("Created topic %s with ARN %s.", name, topic.arn) |
| 44 | except ClientError: |
| 45 | logger.exception("Couldn't create topic %s.", name) |
| 46 | raise |
| 47 | else: |
| 48 | return topic |
| 49 | |
| 50 | # snippet-end:[python.example_code.sns.CreateTopic] |
| 51 | |
| 52 | # snippet-start:[python.example_code.sns.ListTopics] |
| 53 | def list_topics(self): |
| 54 | """ |
| 55 | Lists topics for the current account. |
| 56 | |
| 57 | :return: An iterator that yields the topics. |
| 58 | """ |
| 59 | try: |
| 60 | topics_iter = self.sns_resource.topics.all() |
| 61 | logger.info("Got topics.") |
| 62 | except ClientError: |
| 63 | logger.exception("Couldn't get topics.") |
| 64 | raise |
| 65 | else: |
| 66 | return topics_iter |
| 67 | |
| 68 | # snippet-end:[python.example_code.sns.ListTopics] |
| 69 | |
| 70 | # snippet-start:[python.example_code.sns.DeleteTopic] |
| 71 | @staticmethod |
| 72 | def delete_topic(topic): |
| 73 | """ |
| 74 | Deletes a topic. All subscriptions to the topic are also deleted. |
| 75 | """ |
| 76 | try: |
| 77 | topic.delete() |
| 78 | logger.info("Deleted topic %s.", topic.arn) |
| 79 | except ClientError: |
no outgoing calls