AWS SQS boto3 send_message 返回“dict”对象没有属性“send_message”

Nir*_*uri 4 python amazon-sqs

  • 我是Python新手,而且还在学习中。
  • 我正在编写 python 代码来向 AWS SQS 发送消息
  • 以下是我写的代码

    from boto3.session import Session session = Session(aws_access_key_id='**', aws_secret_access_key='**', region_name='us-west-2') clientz = session.client('sqs') queue = clientz.get_queue_url(QueueName='queue_name') print queue responses = queue.send_message(MessageBody='Test') print(response.get('MessageId'))

    • 运行此代码时会返回

    {u'QueueUrl':' https://us-west-2.queue.amazonaws.com/@@/queue_name','ResponseMetadata ':{'HTTPStatusCode':200,'RequestId':'@@'}}

    回溯(最近一次调用最后):文件“publisher_dropbox.py”,第77行,在response =queue.send_message(MessageBody ='Test')

    AttributeError:“dict”对象没有属性“send_message”

  • 我不确定“dict”对象是什么,因为我没有在任何地方指定它。

moo*_*oot 5

我认为您将 boto3 客户端 send_mesasge Boto3 客户端 send_message与 boto3.resource.sqs 功能 混合在一起 。

首先,对于boto3.client.sqs.send_message,您需要指定QueueUrl。其次,出现错误消息是因为您编写了错误的打印语句。

# print() function think anything follow by the "queue" are some dictionary attributes  
print queue responses = queue.send_message(MessageBody='Test')
Run Code Online (Sandbox Code Playgroud)

此外,我不需要使用 boto3.session ,除非我需要显式定义备用配置文件或访问,而不是在 aws 凭证文件内进行设置。

import boto3 
sqs = boto3.client('sqs') 
queue = sqs.get_queue_url(QueueName='queue_name')
# get_queue_url will return a dict e.g.
# {'QueueUrl':'......'}
# You cannot mix dict and string in print. Use the handy string formatter
# will fix the problem   
print "Queue info : {}".format(queue)

responses = sqs.send_message(QueueUrl= queue['QueueUrl'], MessageBody='Test')
# send_message() response will return dictionary  
print "Message send response : {} ".format(response) 
Run Code Online (Sandbox Code Playgroud)