python - AWS SNS-如何检索confirm_subscription的 token

标签 python amazon-web-services boto3 amazon-sqs amazon-sns

我正在编写一个 python 3.7 脚本来将 SNS 消息定向到 SQS 队列。 创建队列和主题后,我尝试通过调用 sns.subscribe 将 SQS 队列订阅到 SNS 主题:

sns = boto3.client('sns')
subscription = sns.subscribe(
    TopicArn=sns_topic,
    Protocol='sqs',
    Endpoint=sqs_queue_arn,
    ReturnSubscriptionArn=True )

根据documentation :

To actually create a subscription, the endpoint owner must call the ConfirmSubscription action with the token from the confirmation message.

confirm_subscription 的文档从订阅调用中请求 token :

Verifies an endpoint owner's intent to receive messages by validating the token sent to the endpoint by an earlier Subscribe action

    sns.confirm_subscription(
        TopicArn=sns_topic,
        Token= **????????????**
    )

问题是第一次调用 subscribe 不会请求,也不会返回 token 。

知道如何检索 token 吗?
任何帮助将不胜感激!

最佳答案

我目前正在使用 boto3 (1.16.52)、Django (3.1.5) 和 python-dotenv (0.15.0)。我能够使用 POST Controller 中的这个小脚本确认订阅。

#convert body from request in JSON to python dict (Here is the token)
data=json.loads(request.body)
#Access SNS from boto3
sns = boto3.resource('sns',region_name='us-east-1')
#Access with python-dotenv the arn of my topic from my .env file 
#(you can get it from AWS console, is something like arn:aws:sns:region:number:topic )
sns_arn=os.getenv("SNS_ARN")
#get topic
topic = sns.Topic(sns_arn)
#Confirm suscription
if "Token" in data.keys(): 
    topic.confirm_subscription(Token=data["Token"])
    print("confirmation success",flush=True)

不要忘记使用您自己的 SNS_ARN 变量创建并保存 .env 文件。 有关环境变量的更多信息,请检查: python-dotenv 和 boto3: boto3 confirm_suscription

关于python - AWS SNS-如何检索confirm_subscription的 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58826199/

相关文章:

python - 为什么在 python 脚本完成之前不执行打印作业?

python - 在 Python 中将 SHA256 哈希字符串转换为 SHA256 哈希对象

amazon-web-services - 授权 header 代替 x-api-key

amazon-web-services - 无法建立与负载平衡器的安全连接

python - 如何使用 boto3 以文件系统样式检索存储桶前缀

python - Keras model.predict,InvalidArgumentError,ConcatOp : Dimensions of inputs should match

python - 实时向 matlibplot 散点图添加点

amazon-web-services - Amazon CloudSearch - 文档未从索引中删除

python - 为什么这些查询之间的 dynamodb 性能不同?

python - 使用Boto3启动具有IAM角色的EC2实例出现未授权操作错误