AWS:通过boto3发布Lambda函数的SNS消息(Python2)

bmo*_*ran 23 amazon-sns python-2.7 boto3 aws-lambda

我正在尝试发布到SNS主题,然后通知Lambda函数以及SQS队列.我的Lambda函数会被调用,但CloudWatch会记录我的"event"对象是None.boto3文档声明使用kwarg MessageStructure ='json'但会抛出ClientError.

希望我已经提供了足够的信息.

示例代码:

import json
import boto3

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

Rya*_*uck 58

您需要为default消息有效负载添加密钥,并指定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'
)
Run Code Online (Sandbox Code Playgroud)

  • 确定它确实 - 它在dict传递给`Message` arg. (8认同)
  • 如果您使用Python SDK运行它,请说EC2-Instance不要忘记在客户端内添加一个区域,例如`client = boto3.client('sns',region_name ='us-east-1') `https://bradmontgomery.net/blog/sending-sms-messages-amazon-sns-and-python/ (2认同)

Ami*_*mir 19

以防您希望为短信和电子邮件订阅者提供不同的消息:

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'
)
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用Python SDK运行EC2实例,请不要忘记在客户端内部添加区域,例如:client = boto3.client('sns',region_name ='us-east-1') `https://bradmontgomery.net/blog/sending-sms-messages-amazon-sns-and-python/ (2认同)

Ker*_*rem 5

如果您要使用过滤器策略发布消息,您还应该使用 MessageAttributes 参数来添加 SNS 过滤器。

要使用此 SNS 订阅过滤器策略调用 Lambda {"endpoint": ["distance"]}

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',
    MessageAttributes={
                        'foo': {
                            'DataType': 'String',
                            'StringValue': 'bar'
                        }
                    },
)
Run Code Online (Sandbox Code Playgroud)