首页 > 解决方案 > SNS 总是发送默认消息而不是给定的特定协议消息

问题描述

这是代码

message = {
   "default":"Sample fallback message",
   "http":{
      "data":[
         {
            "type":"articles",
            "id":"1",
            "attributes":{
               "title":"JSON:API paints my bikeshed!",
               "body":"The shortest article. Ever.",
               "created":"2015-05-22T14:56:29.000Z",
               "updated":"2015-05-22T14:56:28.000Z"
            }
         }
      ]
   }
}

message_as_json = json.dumps(message)

response = sns_client.publish(TopicArn = "arn:aws:sns:us-east-1:MY-ARN",
            Message = message_as_json, MessageStructure = "json")

print(response)

为了测试,我使用 ngrok 将 localhost(它运行我的烧瓶应用程序)连接到网络并创建了一个 http 订阅。

当我发布消息时,我只能在其中看到默认消息。

知道为什么会这样吗?

标签: pythonamazon-web-servicesamazon-sns

解决方案


您需要http根据 AWS boto3 文档将键的值指定为简单的 JSON 字符串值:

JSON 对象中与支持的传输协议对应的键必须具有简单的 JSON 字符串值。

非字符串值将导致键被忽略。

import json
import boto3

sns_client = boto3.client("sns")

message = {
    "default": "Sample fallback message",
    "http": json.dumps(
        {
            "data": [
                {
                    "type": "articles",
                    "id": "1",
                    "attributes": {
                        "title": "JSON:API paints my bikeshed!",
                        "body": "The shortest article. Ever.",
                        "created": "2015-05-22T14:56:29.000Z",
                        "updated": "2015-05-22T14:56:28.000Z",
                    },
                }
            ]
        }
    ),
}

response = sns_client.publish(
    TopicArn="arn:aws:sns:us-east-1:MY-ARN", Message=json.dumps(message), MessageStructure="json"
)

推荐阅读