Skip to main content
 首页 » 编程设计

python之AWS SQS boto3 send_message 返回 'dict' 对象没有属性 'send_message'

2024年10月24日7webabcd

  • 我是 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': '@@'}}

    Traceback (most recent call last): File "publisher_dropbox.py", line 77, in responses = queue.send_message(MessageBody='Test')

    AttributeError: 'dict' object has no attribute 'send_message'

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

请您参考如下方法:

我认为你混淆了 boto3 客户端 send_mesasge Boto3 client 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') 

此外,我不需要使用 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)