Boto3

https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html
boto3

安装
pip install boto3


指定相应版本
pip install boto3


The latest development version can always be found on GitHub.最新的开发版本


Configuration 配置

在开始使用Boto 3以前,应该设置身份验证凭据。您的AWS账户的凭据能够在IAM控制台中找到。您能够建立或使用现有用户。转到管理访问键并生成一组新的键。html

 

若是您已经安装了AWS CLI,那么您可使用它来配置您的凭据文件:python

aws configure

 

或者,您能够本身建立凭据文件。默认状况下,它的位置在 ~/.aws/credentials:ios

[default] aws_access_key_id = YOUR_ACCESS_KEY aws_secret_access_key = YOUR_SECRET_KEY

 

您可能还须要设置一个默认区域。这能够在配置文件中完成。默认状况下,它的位置在~/.aws/config:git

 

[default] region=us-east-1

或者,您能够在建立客户机和资源时传递region_name。
这将为建立链接时使用的默认配置文件和默认区域设置凭据。有关深刻配置源和选项,请参见凭据。See Credentials 

使用Boto 3github

 import boto3api

 s3 = boto3.resource('s3')#使用Amazon S3session

如今您有了s3资源,就能够发出请求并处理来自服务的响应。下面使用bucket集合打印出全部桶名:多线程

 

for bucket in s3.buckets.all(): print(bucket.name)

上传和下载二进制数据也很容易。例如,下面将一个新文件上传到S3。它假设bucket my-bucket已经存在:

# Upload a new file
data = open('test.jpg', 'rb') s3.Bucket('my-bucket').put_object(Key='test.jpg', Body=data)


Resources and Collections will be covered in more detail in the following sections, so don't worry if you do not completely understand the examples.

资源和集合将在下面的部分中更详细地介绍,因此若是您没有彻底理解这些示例,也没必要担忧。






 

 

 

 

A Sample  Tutorial# 一个示例教程
本教程将向您展现如何在AWS服务中使用Boto3。在本示例教程中,您将了解如何在Amazon Simple Queue Service (SQS)中使用Boto3
This tutorial will show you how to use Boto3 with an AWS service. In this sample tutorial, you will learn how to use Boto3 with Amazon Simple Queue Service (SQS)


SQS容许您排队,而后处理消息。本教程介绍如何建立新队列、获取和使用现有队列、将新消息推送到队列以及经过使用资源和集合处理来自队列的消息。
SQS allows you to queue and then process messages. This tutorial covers how to create a new queue, get and use an
existing queue, push new messages onto the queue, and process messages from the queue by using Resources and
 Collections.

Creating a Queue
建立一个队列

队列是用名称建立的。您还能够选择设置队列属性,例如在处理某项以前等待的秒数。下面的示例将使用队列名称测试。在建立队列以前,您必须首先获取SQS服务资源:


# Get the service resource
sqs = boto3.resource('sqs') # Create the queue. This returns an SQS.Queue instance#建立队列。它返回一个SQS。队列实例 queue = sqs.create_queue(QueueName='test', Attributes={'DelaySeconds': '5'}) # You can now access identifiers and attributes print(queue.url) print(queue.attributes.get('DelaySeconds')) 

Reference: SQS.ServiceResource.create_queue()app

 

Warningcors

The code above may throw an exception if you already have a queue named test.

若是您已经有一个名为test的队列,那么上面的代码可能会抛出一个异常。

 

 

Using  an Existing Queue# 使用现有队列

:能够根据队列的名称查找队列。若是队列不存在,则抛出异常:

# Get the service resource
sqs = boto3.resource('sqs') # Get the queue. This returns an SQS.Queue instance queue = sqs.get_queue_by_name(QueueName='test') # You can now access identifiers and attributes print(queue.url) print(queue.attributes.get('DelaySeconds')) 

It is also possible to list all of your existing queues:

#也能够列出全部现有的队列:

# Print out each queue name, which is part of its ARN#
打印出每一个队列名称,它是其ARN的一部分 for queue in sqs.queues.all(): print(queue.url)

Note

To get the name from a queue, you must use its ARN, which is available in the queue's attributesattribute.

要从队列中获取名称,必须使用它的ARN,该ARN在队列的attributes属性中可用。

Using queue.attributes['QueueArn'].split(':')[-1] will return its name.

Reference: SQS.ServiceResource.get_queue_by_name()SQS.ServiceResource.queues

 

 

Sending Messages

发送消息将它添加到队列的末尾

# Get the service resource
sqs = boto3.resource('sqs') # Get the queue queue = sqs.get_queue_by_name(QueueName='test') # Create a new message response = queue.send_message(MessageBody='world') # The response is NOT a resource, but gives you a message ID and MD5 print(response.get('MessageId')) print(response.get('MD5OfMessageBody'))



You can also create messages with custom attributes:
你能够建立带有自定义属性的消息

queue.send_message(MessageBody='boto3', MessageAttributes={ 'Author': { 'StringValue': 'Daniel', 'DataType': 'String' } })
消息也能够分批发送。例如,在一个请求中发送上面描述的两条消息以下所示:
response = queue.send_messages(Entries=[ { 'Id': '1', 'MessageBody': 'world' }, { 'Id': '2', 'MessageBody': 'boto3', 'MessageAttributes': { 'Author': { 'StringValue': 'Daniel', 'DataType': 'String' } } } ]) # Print out any failures print(response.get('Failed'))

在这种状况下,响应包含成功和失败消息的列表,所以若是须要,您能够重试失败。

In this case, the response contains lists of Successful and Failed messages, so you can retry failures if needed.

Reference: SQS.Queue.send_message()SQS.Queue.send_messages()





Processing Messages 消息处理

Messages are processed in batches: 分批处理消息

 

 

# Get the service resource
sqs = boto3.resource('sqs') # Get the queue queue = sqs.get_queue_by_name(QueueName='test') # Process messages by printing out body and optional author name#经过打印正文和可选做者名来处理消息 for message in queue.receive_messages(MessageAttributeNames=['Author']): # Get the custom author message attribute if it was set#让队列知道消息已被处理 author_text = '' if message.message_attributes is not None: author_name = message.message_attributes.get('Author').get('StringValue') if author_name: author_text = ' ({0})'.format(author_name) # Print out the body and author (if set)打印正文和做者(若是设置) print('Hello, {0}!{1}'.format(message.body, author_text)) # Let the queue know that the message is processed 让队列知道消息已被处理 message.delete()


 

Given only the messages that were sent in a batch with SQS.Queue.send_messages() in the previous section, the above code will print out:

Hello, world!
Hello, boto3! (Daniel)

Reference: SQS.Queue.receive_messages()SQS.Message.delete()

 

 

 

Code Examples
This section provides code examples that demonstrate common Amazon Web Services scenarios using the Amazon Web Services (AWS) SDK for Python.
本节提供的代码示例演示了使用Python的Amazon Web Services (AWS) SDK的常见Amazon Web服务场景。

 

 

 

 

User Guides用户指南

相关文章
相关标签/搜索