aws是Amazon Web Service的简写,它包括众多服务,其中最有名的两个是EC2和S3。

S3是Simple Storage Service的简写,它是一种对象存储的实现。

安装和配置

安装boto3和awscli:pip install boto3 awscli

配置aws:aws configure

根据提示输入access_key_id, secret_access_keyregion

其中access_key_id, secret_access_key的默认存储位置为:~/.aws/credentials

[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY

region的存储位置为~/.aws/config:

[default]
region=us-east-1

快速开始

如下代码,首先创建一个s3服务,然后查看全部Bucket,最后上传一个文件。

import boto3

# Let's use Amazon S3
s3 = boto3.resource('s3')
# Print out bucket names
for bucket in s3.buckets.all():
print(bucket.name)
# Upload a new file
data = open('test.jpg', 'rb')
s3.Bucket('my-bucket').put_object(Key='test.jpg', Body=data)

Code Examples

使用Bucket

创建bucket

如下函数封装boto3的create_bucket(),如果创建Bucket成功,返回True,否则返回False。

import logging
import boto3
from botocore.exceptions import ClientError def create_bucket(bucket_name):
s3 = boto3.client('s3')
try
s3.create_bucket(Bucket=bucket_name)
except ClientError as e:
logging.error(e)
return False
return True

列出bucket

s3 = boto3.client('s3')
response = s3.list_buckets()
print('Existing buckets:')
for bucket in response['Buckets']:
print(f'{bucket["Name"]}')

上传文件

基本用法

s3提供了两种文件上传方式:upload_file()upload_fileobj()upload_file()会把一个大文件拆分成若干个chunk并行上传,因此upload_file()传输速率较快,它适用于上传内容已经确定的文件。upload_fileobj()可用于单线程上传一个二进制流。

upload_file()例子:

import logging
import boto3
from botocore.exceptions import ClientError def upload_file(file_name, bucket, object_name=None):
"""Upload a file to an S3 bucket :param file_name: File to upload
:param bucket: Bucket to upload to
:param object_name: S3 object name. If not specified then file_name is used
:return: True if file was uploaded, else False
""" # If S3 object_name was not specified, use file_name
if object_name is None:
object_name = file_name # Upload the file
s3_client = boto3.client('s3')
try:
response = s3_client.upload_file(file_name, bucket, object_name)
except ClientError as e:
logging.error(e)
return False
return True

upload_fileobj()例子:

s3 = boto3.client('s3')
with open("FILE_NAME", "rb") as f:
s3.upload_fileobj(f, "BUCKET_NAME", "OBJECT_NAME")

upload_fileobj()的文件参数只能是rb模式打开的文件。

Client、Bucket、Object三个类型都提供了upload_file()upload_fileobj()两个函数,每个类型提供的同一函数功能都是等价的,并无优劣之分,可以随意调用三个对象的上传文件函数。

ExtraArgs

ExtraArgs提供了上传文件的其它参数,这些参数可用于控制上传文件的读写权限、meta信息等。S3Transfer是一个非常重要的对象,它定义了传输过程中的许多参数,在

boto3.s3.transfer.S3Transfer.ALLOWED_UPLOAD_ARGS中,定义了ExtraArgs可用的参数列表。

s3.upload_file(
'FILE_NAME', 'BUCKET_NAME', 'OBJECT_NAME',
ExtraArgs={'Metadata': {'mykey': 'myvalue'}}
)
s3.upload_file(
'FILE_NAME', 'BUCKET_NAME', 'OBJECT_NAME',
ExtraArgs={'ACL': 'public-read'}
)
s3.upload_file(
'FILE_NAME', 'BUCKET_NAME', 'OBJECT_NAME',
ExtraArgs={
'GrantRead': 'uri="http://acs.amazonaws.com/groups/global/AllUsers"',
'GrantFullControl': 'id="01234567890abcdefg"',
}
)

上传过程的回调函数

一边上传一边打印上传进度可以通过实现Callback回调来实现。

s3.upload_file(
'FILE_NAME', 'BUCKET_NAME', 'OBJECT_NAME',
Callback=ProgressPercentage('FILE_NAME')
)

ProgressPercentage

import os
import sys
import threading class ProgressPercentage(object): def __init__(self, filename):
self._filename = filename
self._size = float(os.path.getsize(filename))
self._seen_so_far = 0
self._lock = threading.Lock() def __call__(self, bytes_amount):
# To simplify, assume this is hooked up to a single filename
with self._lock:
self._seen_so_far += bytes_amount
percentage = (self._seen_so_far / self._size) * 100
sys.stdout.write(
"\r%s %s / %s (%.2f%%)" % (
self._filename, self._seen_so_far, self._size,
percentage))
sys.stdout.flush()

下载文件

下载文件和上传文件几乎是完全对称的,Client、Bucket、Object三个对象提供了download_file()download_fileobj()download_file()是并行的,download_file_obj()是串行的,这两个函数同样提供了ExtraArgs和Callback参数。boto3.s3.transfer.S3Transfer.ALLOWED_DOWNLOAD_ARGS描述了下载过程的ExtraArgs的可用参数。

import boto3

s3 = boto3.client('s3')
s3.download_file('BUCKET_NAME', 'OBJECT_NAME', 'FILE_NAME') with open('FILE_NAME', 'wb') as f:
s3.download_fileobj('BUCKET_NAME', 'OBJECT_NAME', f)

传输配置

在上传文件、下载文件、复制文件过程中,AWS SDK会自动管理重试等网络配置。默认的网络配置可适用于大多数情况,只有特殊情境下才需要修改传输配置。

传输配置封装在 boto3.s3.transfer.TransferConfig对象中,upload_file()等函数都有一个Config参数接受一个TransferConfig对象。

修改multipart阈值

当使用upload_file()上传一个大文件时,如果文件大小超过了multipart_threshold,那么会启动多线程上传。

import boto3
from boto3.s3.transfer import TransferConfig # Set the desired multipart threshold value (5GB)
GB = 1024 ** 3
config = TransferConfig(multipart_threshold=5*GB) # Perform the transfer
s3 = boto3.client('s3')
s3.upload_file('FILE_NAME', 'BUCKET_NAME', 'OBJECT_NAME', Config=config)

设置并发数

对于upload_file()download_file()默认启用多线程下载,为了减少网络占用或者增加网络占用,可以通过传输配置来控制。

# To consume less downstream bandwidth, decrease the maximum concurrency
config = TransferConfig(max_concurrency=5) # Download an S3 object
s3 = boto3.client('s3')
s3.download_file('BUCKET_NAME', 'OBJECT_NAME', 'FILE_NAME', Config=config)

设置并发的实现方式

在boto3中,并发是通过多线程来实现的。如果不使用线程就没法实现并发,max_concurrency参数会被忽略掉。

# Disable thread use/transfer concurrency
config = TransferConfig(use_threads=False) s3 = boto3.client('s3')
s3.download_file('BUCKET_NAME', 'OBJECT_NAME', 'FILE_NAME', Config=config)

将一个Bucket作为一个静态服务

获取一个桶的静态服务配置

import boto3

# Retrieve the website configuration
s3 = boto3.client('s3')
result = s3.get_bucket_website('BUCKET_NAME')

设置一个桶的静态服务配置

# Define the website configuration
website_configuration = {
'ErrorDocument': {'Key': 'error.html'},
'IndexDocument': {'Suffix': 'index.html'},
} # Set the website configuration
s3 = boto3.client('s3')
s3.put_bucket_website('BUCKET_NAME', website_configuration)

删除一个桶的网站配置

# Delete the website configuration
s3 = boto3.client('s3')
s3.delete_bucket_website('BUCKET_NAME')

获取一个Bucket的权限列表

import boto3

# Retrieve a bucket's ACL
s3 = boto3.client('s3')
result = s3.get_bucket_acl(Bucket='my-bucket')
print(result)

presigned URL

分享一个Object

import logging
import boto3
from botocore.exceptions import ClientError def create_presigned_url(bucket_name, object_name, expiration=3600):
"""Generate a presigned URL to share an S3 object :param bucket_name: string
:param object_name: string
:param expiration: Time in seconds for the presigned URL to remain valid
:return: Presigned URL as string. If error, returns None.
""" # Generate a presigned URL for the S3 object
s3_client = boto3.client('s3')
try:
response = s3_client.generate_presigned_url('get_object',
Params={'Bucket': bucket_name,
'Key': object_name},
ExpiresIn=expiration)
except ClientError as e:
logging.error(e)
return None # The response contains the presigned URL
return response

直接使用GET请求这个URL:

import requests    # To install: pip install requests

url = create_presigned_url('BUCKET_NAME', 'OBJECT_NAME')
if url is not None:
response = requests.get(url)

其它技巧

桶策略

IAP:Identity&Access Policy

查询一个桶的权限

import boto3

# Retrieve the policy of the specified bucket
s3 = boto3.client('s3')
result = s3.get_bucket_policy('BUCKET_NAME')
print(result['Policy'])

设置一个桶策略

import json

# Create a bucket policy
bucket_name = 'BUCKET_NAME'
bucket_policy = {
'Version': '2012-10-17',
'Statement': [{
'Sid': 'AddPerm',
'Effect': 'Allow',
'Principal': '*',
'Action': ['s3:GetObject'],
'Resource': f'arn:aws:s3:::{bucket_name}/*'
}]
} # Convert the policy from JSON dict to string
bucket_policy = json.dumps(bucket_policy) # Set the new policy
s3 = boto3.client('s3')
s3.put_bucket_policy(bucket_name, Policy=bucket_policy)

删除桶策略

# Delete a bucket's policy
s3 = boto3.client('s3')
s3.delete_bucket_policy('BUCKET_NAME')

重要包介绍

boto3根包

boto3根包提供了两类API:全局设置、重要入口类。

全局设置包括:

  • boto3.set_stream_logger(name='boto3', level=10, format_string=None)设置日志级别
  • boto3.setup_default_session(**kwargs)设置默认session

重要入口类包括:

  • boto3.resource(*args, **kwargs):最终会调用session包下的resource函数boto3.session.Session.resource()
  • boto3.client(*args, **kwargs):最终会调用session包下的resource函数boto3.session.Session.client()

collection包

boto3中的许多事物最终都可以看做一个集合,例如所有的Bucket构成一个集合,一个目录下的全部Object构成一个集合。collection包指的是boto3.resources.collection

collection包主要提供两个入口类:CollectionManagerResourceCollection。这两个类几乎具有完全一样的方法:

  • all():获取全部对象的迭代器
  • filter():过滤对象
  • limit(count):只读取count个对象
  • page_size(count)和pages()用于分页

resource包

boto3.resource包下内容较多,它包括请求和回复的格式等类型。

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/resources.html

session包

boto3.session包只包含一个Session类,这个类是整个boto库的入口类。一个Session对象相当于一个包含了各种基础配置的对象(如aws_access_key_id、aws_secret_access_key等),利用此对象可以获取到Client、Resource等对象。

利用Session可以获取一些全局信息

  • get_available_partitions():获取可用分区列表
  • get_available_regions():获取可用region列表
  • available_profiles:获取可用的配置文件目录
  • get_available_regions(service_name, partition_name='aws', allow_non_regional=False):获取可用分区
  • get_available_resources():获取可用资源列表,也就是可以用sess.resource(service_name)函数获取的服务列表
  • get_awailable_services():获取可用服务列表,也就是可以用sess.client(service_name)函数获取的服务列表
  • get_credentials():和此session有关的秘钥,使用botocore.credential.Credential对象存储。

利用Session可以构建最重要的两个入口类:

resource(service_name, region_name=None, api_version=None, use_ssl=True, verify=None, endpoint_url=None, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, config=None)

client(service_name, region_name=None, api_version=None, use_ssl=True, verify=None, endpoint_url=None, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, config=None)

boto3.s3.transfer

boto3.s3.transfer包下包含两个类:TransferConfig和S3Transfer。TransferConfig对象可作为upload_file()的Config参数的取值;S3Transfer对象实现了upload_file()download_file(),实际上Client、Bucket、Object等类最终都会调用这两个函数,S3Transfer还提供了两个常量表示上传下载时可接受的参数:ALLOWED_DOWNLOAD_ARGS和ALLOWED_UPLOAD_ARGS。

class boto3.s3.transfer.TransferConfig(multipart_threshold=8388608, max_concurrency=10, multipart_chunksize=8388608, num_download_attempts=5, max_io_queue=100, io_chunksize=262144, use_threads=True)

class boto3.s3.transfer.S3Transfer(client=None, config=None, osutil=None, manager=None)
ALLOWED_DOWNLOAD_ARGS = ['VersionId', 'SSECustomerAlgorithm', 'SSECustomerKey', 'SSECustomerKeyMD5', 'RequestPayer']
ALLOWED_UPLOAD_ARGS = ['ACL', 'CacheControl', 'ContentDisposition', 'ContentEncoding', 'ContentLanguage', 'ContentType', 'Expires', 'GrantFullControl', 'GrantRead', 'GrantReadACP', 'GrantWriteACP', 'Metadata', 'RequestPayer', 'ServerSideEncryption', 'StorageClass', 'SSECustomerAlgorithm', 'SSECustomerKey', 'SSECustomerKeyMD5', 'SSEKMSKeyId', 'WebsiteRedirectLocation']
download_file(bucket, key, filename, extra_args=None, callback=None)
upload_file(filename, bucket, key, callback=None, extra_args=None)[source]

用户指南

boto3官网教程中的用户指南描述了boto3中的各个实体,是最终的文档。

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

boto3提供了两个级别的接口来访问AWS服务:High Level的Resource级别的接口,Low Level的Client接口。

Client级别的接口返回Dictionary来表示查询到的资源信息,Resource级别的接口对Client级别的接口进行了面向对象的封装,接口的返回值大部分都是Resource对象(如果返回值是某个Resource的信息的话),我们可以对返回的对象再进行操作(比如删除,修改等)。

Resource

Resource对象是AWS服务的面向对象封装,它提供了比Client更抽象、更高级的封装。

每个Resource对象都包含若干属性和方法,这些属性和方法可以分为以下几大类别: identifiers, attributes, actions, references, sub-resources, 和 collections。

Resource对象可以被分为两类:

  • 服务对象(Service Resource):例如 sqs, s3, ec2
  • 独立对象(Indivisual Resource):例如sqs.Queue 、 s3.Bucket

服务对象和独立对象的区别在于:服务对象没有identifiers和attributes之类的属性和方法。

Collection

Collection对象和Django中的QuerySets非常像。

Client

Client对象提供了最底层的AWS服务封装,这些服务操作和AWS服务定义是一一对应的。实际上,Client类型的代码是由JSON形式的服务说明文件直接生成的。

Paginator分页

有些请求返回的对象太多,所以不能一次性全部返回,只能使用迭代的方式进行访问。

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

Configuration

boto3会依次查找如下位置的配置,直到找到配置为止(也就是如下配置优先级递减):

  • boto.client()方法中的参数
  • 创建session时传递的参数
  • 环境变量
  • Shared credential file (~/.aws/credentials)
  • AWS config file (~/.aws/config)
  • Assume Role provider
  • Boto2 config file (/etc/boto.cfg and ~/.boto)
  • Instance metadata service on an Amazon EC2 instance that has an IAM role configured.

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

使用技巧

content-range随机读取,相当于C语言中的fseek:https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16

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

S3 API

boto3用法的更多相关文章

  1. EditText 基本用法

    title: EditText 基本用法 tags: EditText,编辑框,输入框 --- EditText介绍: EditText 在开发中也是经常用到的控件,也是一个比较必要的组件,可以说它是 ...

  2. jquery插件的用法之cookie 插件

    一.使用cookie 插件 插件官方网站下载地址:http://plugins.jquery.com/cookie/ cookie 插件的用法比较简单,直接粘贴下面代码示例: //生成一个cookie ...

  3. Java中的Socket的用法

                                   Java中的Socket的用法 Java中的Socket分为普通的Socket和NioSocket. 普通Socket的用法 Java中的 ...

  4. [转载]C#中MessageBox.Show用法以及VB.NET中MsgBox用法

    一.C#中MessageBox.Show用法 MessageBox.Show (String) 显示具有指定文本的消息框. 由 .NET Compact Framework 支持. MessageBo ...

  5. python enumerate 用法

    A new built-in function, enumerate() , will make certain loops a bit clearer. enumerate(thing) , whe ...

  6. [转载]Jquery中$.get(),$.post(),$.ajax(),$.getJSON()的用法总结

    本文对Jquery中$.get(),$.post(),$.ajax(),$.getJSON()的用法进行了详细的总结,需要的朋友可以参考下,希望对大家有所帮助. 详细解读Jquery各Ajax函数: ...

  7. 【JavaScript】innerHTML、innerText和outerHTML的用法区别

    用法: <div id="test">   <span style="color:red">test1</span> tes ...

  8. chattr用法

    [root@localhost tmp]# umask 0022 一.chattr用法 1.创建空文件attrtest,然后删除,提示无法删除,因为有隐藏文件 [root@localhost tmp] ...

  9. 萌新笔记——vim命令“=”、“d”、“y”的用法(结合光标移动命令,一些场合会非常方便)

    vim有许多命令,网上搜有一堆贴子.文章列举出各种功能的命令. 对于"="."d"."y",我在无意中发现了它们所具有的相同的一些用法,先举 ...

随机推荐

  1. 爬虫---Beautiful Soup 爬取图片

    上一篇简单的介绍Beautiful Soup 的基本用法,这一篇写下如何爬取网站上的图片,并保存下来 爬取图片 1.找到一个福利网站:http://www.xiaohuar.com/list-1-1. ...

  2. Mysqldump一次备份多个指定数据库

    今天碰到了,就作个记录. mysqldump -u user -p --databases DB1 DB2 --single-transaction --master-data=2 --default ...

  3. 4-剑指offer: 把数组排成最小的数

    题目描述 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个.例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323. 代码: cl ...

  4. Java中用import导入类和用Class方法加载类有什么区别?

    import仅仅包含导入操作,并不包含将字节码文件加载进内存这一动作,将字节码文件加载进内存是后续的实例化操作完成的. 例如通过import导入了一堆包和类,但是后续什么都没用(没用实例化),那么导入 ...

  5. 201777010217-金云馨《面向对象程序设计(java)》第十三周学习

    项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...

  6. python27期day05:字典、字典嵌套、作业题。

    1.字典是python中的数据类型之一.唯一一种大括号{}键值对的数据. 2.存储大量的数据.将数据和数据之间进行关联. 3.通过键可以准确的找到值 4.哈希:可变数据类型就不可哈希   不可变数据类 ...

  7. scrapy机制mark(基于twisted)

    twisted twisted管理了所有的异步任务 Twisted的主线程是单线程的,即reactor线程: 而这些io耗时操作会在线程池中运行,不再twisted主线程中运行,即通过线程池来执行异步 ...

  8. [LeetCode] 33. Search in Rotated Sorted Array 在旋转有序数组中搜索

    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e. ...

  9. KMP 串的模式匹配 (25分)

    给定两个由英文字母组成的字符串 String 和 Pattern,要求找到 Pattern 在 String 中第一次出现的位置,并将此位置后的 String 的子串输出.如果找不到,则输出“Not ...

  10. python实现的WebSocket客户端

    code #coding=utf- import json import time from websocket import create_connection ws = create_connec ...