如何使用主题名称通过Boto3在Python中发布SNS消息来获得SNS主题ARN



Python

运行查询的方法

def function(run_query)
//topic = arn return from topic name
topic.publish(message)
pass

我正在使用boto3资源方法。使用boto3.client的例子很多,使用boto3资源方法实现sns方法的例子有限。

似乎没有简单的、预期的get_topic_arn(topic_name)方法可以通过Boto3 SNS客户端或资源使用主题名称获取AWS主题ARN。

然而,一个聪明的解决方法是使用create_topic方法:

此操作是幂等,因此如果请求者已经拥有指定名称的主题则返回主题的ARN而不创建新主题。

使用现有主题名称调用create_topic,该名称将检索SNS.Topic子资源,然后调用主题子资源上的publish方法

import boto3
sns = boto3.resource('sns')
topic = sns.create_topic(Name='MyTopicName')
topic_arn = topic.arn
response = topic.publish(Message='MyMessage')
...

最新更新