1. https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.htmlboto3
  2.  
  3. 安装pip install boto3
  4.  
  5. 指定相应版本pip install boto3
  6.  
  7. The latest development version can always be found on GitHub.最新的开发版本
  8.  

Configuration 配置

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

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

  1. aws configure

或者,您可以自己创建凭据文件。默认情况下,它的位置在 ~/.aws/credentials:

  1. [default]
  2. aws_access_key_id = YOUR_ACCESS_KEY
  3. aws_secret_access_key = YOUR_SECRET_KEY

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

  1. [default]
  2. region=us-east-1
  3.  
  4. 或者,您可以在创建客户机和资源时传递region_name。这将为创建连接时使用的默认配置文件和默认区域设置凭据。有关深入配置源和选项,请参见凭据。See Credentials 

使用Boto 3

 import boto3

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

现在您有了s3资源,就可以发出请求并处理来自服务的响应。下面使用bucket集合打印出所有桶名:

  1. for bucket in s3.buckets.all():
  2. print(bucket.name)
  3.  
  4. 上传和下载二进制数据也很容易。例如,下面将一个新文件上传到S3。它假设bucket my-bucket已经存在:
  1. # Upload a new file
  2. data = open('test.jpg', 'rb')
  3. s3.Bucket('my-bucket').put_object(Key='test.jpg', Body=data)
  4.  
  5. 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.
  6.  
  7. 资源和集合将在下面的部分中更详细地介绍,所以如果您没有完全理解这些示例,也不必担心。
  8.  
  1.  
  1. A Sample Tutorial# 一个示例教程本教程将向您展示如何在AWS服务中使用Boto3。在本示例教程中,您将了解如何在Amazon Simple Queue Service (SQS)中使用Boto3This 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)
  2.  
  3. 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.
  4.  
  5. Creating a Queue创建一个队列
  6.  
  7. 队列是用名称创建的。您还可以选择设置队列属性,例如在处理某项之前等待的秒数。下面的示例将使用队列名称测试。在创建队列之前,您必须首先获取SQS服务资源:
  8.  
  1. # Get the service resource
  2. sqs = boto3.resource('sqs')
  3.  
  4. # Create the queue. This returns an SQS.Queue instance#创建队列。它返回一个SQS。队列实例
  5. queue = sqs.create_queue(QueueName='test', Attributes={'DelaySeconds': '5'})
  6.  
  7. # You can now access identifiers and attributes
  8. print(queue.url)
  9. print(queue.attributes.get('DelaySeconds'))

Reference: SQS.ServiceResource.create_queue()

Warning

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

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

Using  an Existing Queue# 使用现有队列

:可以根据队列的名称查找队列。如果队列不存在,则抛出异常:

  1. # Get the service resource
  2. sqs = boto3.resource('sqs')
  3.  
  4. # Get the queue. This returns an SQS.Queue instance
  5. queue = sqs.get_queue_by_name(QueueName='test')
  6.  
  7. # You can now access identifiers and attributes
  8. print(queue.url)
  9. print(queue.attributes.get('DelaySeconds'))

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

#也可以列出所有现有的队列:

  1. # Print out each queue name, which is part of its ARN#打印出每个队列名称,它是其ARN的一部分
  2. for queue in sqs.queues.all():
  3. 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

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

  1. # Get the service resource
  2. sqs = boto3.resource('sqs')
  3.  
  4. # Get the queue
  5. queue = sqs.get_queue_by_name(QueueName='test')
  6.  
  7. # Create a new message
  8. response = queue.send_message(MessageBody='world')
  9.  
  10. # The response is NOT a resource, but gives you a message ID and MD5
  11. print(response.get('MessageId'))
  12. print(response.get('MD5OfMessageBody'))
  13.  
  14. You can also create messages with custom attributes:你可以创建带有自定义属性的消息
  1. queue.send_message(MessageBody='boto3', MessageAttributes={
  2. 'Author': {
  3. 'StringValue': 'Daniel',
  4. 'DataType': 'String'
  5. }
  6. })消息也可以分批发送。例如,在一个请求中发送上面描述的两条消息如下所示:
  1. response = queue.send_messages(Entries=[
  2. {
  3. 'Id': '1',
  4. 'MessageBody': 'world'
  5. },
  6. {
  7. 'Id': '2',
  8. 'MessageBody': 'boto3',
  9. 'MessageAttributes': {
  10. 'Author': {
  11. 'StringValue': 'Daniel',
  12. 'DataType': 'String'
  13. }
  14. }
  15. }
  16. ])
  17.  
  18. # Print out any failures
  19. print(response.get('Failed'))
  1. 在这种情况下,响应包含成功和失败消息的列表,因此如果需要,您可以重试失败。

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()

  1.  

Processing Messages 消息处理

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

  1. # Get the service resource
  2. sqs = boto3.resource('sqs')
  3.  
  4. # Get the queue
  5. queue = sqs.get_queue_by_name(QueueName='test')
  6.  
  7. # Process messages by printing out body and optional author name#通过打印正文和可选作者名来处理消息
  8. for message in queue.receive_messages(MessageAttributeNames=['Author']):
  9. # Get the custom author message attribute if it was set#让队列知道消息已被处理
  10. author_text = ''
  11. if message.message_attributes is not None:
  12. author_name = message.message_attributes.get('Author').get('StringValue')
  13. if author_name:
  14. author_text = ' ({0})'.format(author_name)
  15.  
  16. # Print out the body and author (if set)打印正文和作者(如果设置)
  17. print('Hello, {0}!{1}'.format(message.body, author_text))
  18.  
  19. # Let the queue know that the message is processed 让队列知道消息已被处理
  20. message.delete()
  21.  

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:

  1. Hello, world!
  2. Hello, boto3! (Daniel)

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

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

General Feature Guides# 一般功能指南

 
 

Boto3的更多相关文章

  1. AWS Python SDK boto3中的基本概念与使用方法

    最近在用boto3编写AWS的lamda函数,学习到了boto3中的一些基本概念与使用方法.在此进行总结. 1. boto3提供了两个级别的接口来访问AWS服务:High Level的Resource ...

  2. AWS 命令行界面 + Python 的 AWS 开发工具包 (Boto3)

    安装AWS CLI $ pip install awscli 安装Boto3 $ pip install boto3 设置AWS CLI $ aws configure AWS Access Key ...

  3. 基于python2.7通过boto3实现ec2表格化

    #!/usr/bin/env python import xlwt,xlrd,datetime,json,os,xlutils.copy a={ 'VpcPeeringConnection': { ' ...

  4. boto3库限速

    # -*- coding: utf-8 -*- import boto3 from boto3.s3.transfer import TransferConfig # from s3transfer. ...

  5. 封装boto3 api用于服务器端与AWS S3交互

    由于使用AWS的时候,需要S3来存储重要的数据. 使用Python的boto3时候,很多重要的参数设置有点繁琐. 重新写了一个类来封装操作S3的api.分享一下: https://github.com ...

  6. Python使用boto3操作AWS S3中踩过的坑

    最近在AWS上开发部署应用. 看了这篇关于AWS中国区填坑的文章,结合自己使用AWS的经历,补充两个我自己填的坑. http://www.jianshu.com/p/0d0fd39a40c9?utm_ ...

  7. boto3用法

    aws是Amazon Web Service的简写,它包括众多服务,其中最有名的两个是EC2和S3. S3是Simple Storage Service的简写,它是一种对象存储的实现. 安装和配置 安 ...

  8. rgw使用boto3生成可以访问的预签名url

    前言 如果想访问一个ceph里面的s3地址,但是又不想直接提供secrect key的时候,可以通过预签名的方式生成url 生成方法 下载boto3 脚本如下 cat s3.py import bot ...

  9. Boto3访问AWS资源操作总结(1)

    最近在工作中需要对AWS上的部分资源进行查询和交叉分析,虽然场景都比较简单,但是这种半机械的工作当然还是交给Python来搞比较合适.AWS为Python提供的SDK库叫做boto3,所以我们建立一个 ...

随机推荐

  1. 团队第九次 # scrum meeting

    github 本此会议项目由PM召开,召开时间为4-14日晚上9点,以大家在群里讨论为主 召开时长10分钟 任务表格 袁勤 负责协调前后端 https://github.com/buaa-2016/p ...

  2. 【BZOJ2054】疯狂的馒头(并查集)

    /* 经典思路, 倒序并查集处理即可 */ #include<cstdio> #include<algorithm> #include<cstring> #incl ...

  3. sql_demo

    SELECT M.INSTNCODE, M.METHODCODE, M.CCYPAIRCODE, M.DIR, M.PRD, M.EXCHANGERATE, M.NEARRSKAMOUNT, M.TR ...

  4. Hexo:创建属于你自己的博客

    step: 1.install node.js,git,github 2.npm install -g hexo-cli 3.mkdir hexo 4.cd hexo mkdir blog 5.cd ...

  5. echarts统计图Y轴(或X轴)文字过长问题解决

    echarts 统计图Y轴文字过长 在使用echarts时,出现数值非常大,Y轴又显示不下的情况就需要压缩Y轴数值刻度. 解决方法: yAxis: { type: 'value', axisLabel ...

  6. jquery选择器问题(找东西超级有用)

    $("[class='slider-container theme-green']").css('width','100%');就这么一行代码,很简单,这样就很容易找到唯一元素

  7. azkaban使用--schedule定时任务

    1.schedule azkaban的schedule内部就是集成的quartz,而 quartz语法就是沿用linux crontab,crontab可照本文第2点 此处以此project(azka ...

  8. Python paramiko模块基本使用(一)

    使用paramiko模块登录远程主机,对日志进行统计分析. import paramiko def batch_count(days, hours, ips, user, passwd, source ...

  9. Nginx性能调优之buffer参数设置

    Nginx 的缓存功能有:proxy_cache / fastcgi_cache proxy_cache的作用是缓存后端服务器的内容,可能是任何内容,包括静态的和动态.fastcgi_cache的作用 ...

  10. 【转】如何用Eclispe调试java -jar xxx.jar 方式执行的jar包

    原文地址:https://www.cnblogs.com/zzpbuaa/p/5443269.html 有时候,我们经常会需要调试 java -jar xxx.jar方式运行的代码,而不是必须在Ecl ...