基于主题名称验证是否存在主题

2024-10-04 11:26:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在根据主题名验证是否存在主题。在

你知道这是否可能吗?在

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

下面是我正在尝试的,但不起作用,因为topicsList包含topicArns而不是topicNames。。。在

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

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

Tags: intest主题getifallprintsns
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)

如果你有超过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

如果您试图捕获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"

相关问题 更多 >