AWS: Publish SNS message for Lambda function via boto3 (Python2)

女生的网名这么多〃 提交于 2019-12-20 10:02:47

问题


I am trying to publish to an SNS topic which will then notify a Lambda function, as well as an SQS queue. My Lambda function does get called, but the CloudWatch logs state that my "event" object is None. The boto3 docs states to use the kwarg MessageStructure='json' but that throws a ClientError.

Hopefully I've supplied enough information.

Example Code:

import json
import boto3

message = {"foo": "bar"}
client = boto3.client('sns')
response = client.publish(
    TargetArn=arn,
    Message=json.dumps(message)
)

回答1:


you need to add a default key to your message payload, and specify MessageStructure:

import json
import boto3

message = {"foo": "bar"}
client = boto3.client('sns')
response = client.publish(
    TargetArn=arn,
    Message=json.dumps({'default': json.dumps(message)}),
    MessageStructure='json'
)



回答2:


Just in case you want to have different messages for sms and email subscribers:

import json
import boto3

message = {"foo": "bar"}
client = boto3.client('sns')
response = client.publish(
    TargetArn=arn,
    Message=json.dumps({'default': json.dumps(message),
                        'sms': 'here a short version of the message',
                        'email': 'here a longer version of the message'}),
    Subject='a short subject for your message',
    MessageStructure='json'
)


来源:https://stackoverflow.com/questions/34029251/aws-publish-sns-message-for-lambda-function-via-boto3-python2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!