根据主题名称验证主题是否存在

时间:2015-05-14 17:32:46

标签: python amazon-web-services boto

我正在尝试根据主题名称验证某个主题是否存在。

你知道这是否可能吗?

例如,我想验证名称为“test”的主题是否已存在。

以下是我正在尝试但不起作用的原因因为topicsList包含topicArns而不是topicNames ...

topics = sns.get_all_topics()   
topicsList = topics['ListTopicsResponse']['ListTopicsResult'['Topics']

if "test" in topicsList:
    print("true")

3 个答案:

答案 0 :(得分:4)

如果您有超过100个主题

,此代码将有效
def get_topic(token=None):
    topics = self.sns.get_all_topics(token)
    next_token = topics['ListTopicsResponse']['ListTopicsResult']['NextToken']
    topic_list = topics['ListTopicsResponse']['ListTopicsResult']['Topics']
    for topic in topic_list:
        if "your_topic_name" in topic['TopicArn'].split(':')[5]:
            return topic['TopicArn']
    else:
        if next_token:
            get_topic(next_token)
        else:
            return None

答案 1 :(得分:3)

这是一种黑客行为,但它应该有效:

topics = sns.get_all_topics()   
topic_list = topics['ListTopicsResponse']['ListTopicsResult']['Topics']
topic_names = [t['TopicArn'].split(':')[5] for t in topic_list]

if 'test' in topic_names:
   print(True)

答案 2 :(得分:3)

如果您尝试捕获An error occurred (NotFound) when calling the GetTopicAttributes operation: Topic does not exist例外该怎么办?

from botocore.exceptions import ClientError

topic_arn = "arn:aws:sns:us-east-1:999999999:neverFound"

try:
    response = client.get_topic_attributes(
        TopicArn=topic_arn
    )
    print "Exists"
except ClientError as e:
    # Validate if is this:
    # An error occurred (NotFound) when calling the GetTopicAttributes operation: Topic does not exist
    print "Does not exists"