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用戶指南

相關文章
相關標籤/搜索