安装配置环境
通过AWS的Identity and Access Management新建用户,并授予相应权限,记录其aws_access_key_id及aws_secret_access_key。
安装boto3:
pip install boto3 安装awscli进行管理:
sudo apt install awscli安装完毕后,可以通过aws configure进行系统配置,配置aws_access_key_id及aws_secret_access_key,以及region。如果不通过命令行配置,可以手工进行录入设置。
~/.aws/credentials:
[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY
~/.aws/config:
[default]
region=us-east-1其中region必须配置,否则无法运行。配置后如果使用jupyter,需要重新启动。
使用boto3管理
创建主题(create topic)
import boto3
sns = boto3.client('sns')
response = sns.create_topic(Name='my-topic')
print(response)列示主题(list topic)
import boto3
# Create an SNS client
sns = boto3.client('sns')
# Call SNS to list topics
response = sns.list_topics()
# Get a list of all topic ARNs from the response
topics = [topic['TopicArn'] for topic in response['Topics']]
# Print out the topic list
print("Topic List: %s" % topics)
发布主题(publish topic)
import boto3
# Create an SNS client
sns = boto3.client('sns')
# Publish a simple message to the specified SNS topic
response = sns.publish(
TopicArn='arn:aws:sns:region:0123456789:my-topic-arn',
Message='Hello World!',
)
# Print out the response
print(response)
相关链接:https://docs.aws.amazon.com/code-samples/latest/catalog/code-catalog-python-example_code-sns.html