如何使用boto3将S3对象保存到文件中

182

我正在尝试使用新的boto3客户端与AWS进行“hello world”。

我的用例非常简单:从S3获取对象并将其保存到文件中。

在boto 2.X中,我会这样做:

import boto
key = boto.connect_s3().get_bucket('foo').get_key('foo')
key.get_contents_to_filename('/tmp/foo')

在 boto 3 中,我找不到一个简便的方法来完成同样的事情,因此我正在手动迭代“Streaming”对象:

import boto3
key = boto3.resource('s3').Object('fooo', 'docker/my-image.tar.gz').get()
with open('/tmp/my-image.tar.gz', 'w') as f:
    chunk = key['Body'].read(1024*8)
    while chunk:
        f.write(chunk)
        chunk = key['Body'].read(1024*8)
或者
import boto3
key = boto3.resource('s3').Object('fooo', 'docker/my-image.tar.gz').get()
with open('/tmp/my-image.tar.gz', 'w') as f:
    for chunk in iter(lambda: key['Body'].read(4096), b''):
        f.write(chunk)

它工作得很好。我想知道是否有任何“本地”的boto3函数可以执行相同的任务?

7个回答

297

最近Boto3进行了一项自定义工作,可以帮助解决这个问题(以及其他问题)。它目前在低级别的S3客户端中公开,并且可以像这样使用:

s3_client = boto3.client('s3')
open('hello.txt').write('Hello, world!')

# Upload the file to S3
s3_client.upload_file('hello.txt', 'MyBucket', 'hello-remote.txt')

# Download the file from S3
s3_client.download_file('MyBucket', 'hello-remote.txt', 'hello2.txt')
print(open('hello2.txt').read())

这些函数将自动处理文件的读写以及对大文件进行并行的多部分上传。

请注意,s3_client.download_file不会创建目录。可以使用pathlib.Path('/path/to/file.txt').parent.mkdir(parents=True, exist_ok=True)来创建目录。


1
@Daniel:感谢您的回复。如果我想使用boto3进行多部分上传以上传文件,您能否回答这个问题? - Rahul KP
2
@RahulKumarPatle,“upload_file”方法将自动为大文件使用多部分上传。 - Daniel
5
你如何使用这种方法传递你的凭据? - JHowIX
4
我无法理解为什么.upload_file.download_file的参数顺序不同。 - Vlad M
3
@VladNikiporoff "从源上传到目标" "从源下载到目标" - jkdev
显示剩余3条评论

86

boto3现在比客户端拥有更好的接口:

resource = boto3.resource('s3')
my_bucket = resource.Bucket('MyBucket')
my_bucket.download_file(key, local_filename)

这本身并没有比已接受答案里的client更好(虽然文档说在上传和下载失败时它做了更好的重试),但考虑到资源通常更加人性化(例如,s3bucketobject资源比客户端方法更好),因此这允许您保持在资源层而不必下降。

Resources一般可以像客户端一样创建,并且接受所有或大多数相同的参数,并将它们转发到其内部客户端。


1
很好的例子,补充一下,由于原问题是关于保存对象的,这里相关的方法是 my_bucket.upload_file()(如果你有一个 BytesIO 对象,则使用 my_bucket.upload_fileobj())。 - SMX
2
文档确切地在哪里说resource在重试方面做得更好?我找不到任何这样的提示。 - Asclepius

48

如果您想模拟类似于boto2方法的set_contents_from_string,可以尝试使用

import boto3
from cStringIO import StringIO

s3c = boto3.client('s3')
contents = 'My string to save to S3 object'
target_bucket = 'hello-world.by.vor'
target_file = 'data/hello.txt'
fake_handle = StringIO(contents)

# notice if you do fake_handle.read() it reads like a file handle
s3c.put_object(Bucket=target_bucket, Key=target_file, Body=fake_handle.read())

针对Python3:

在Python3中,StringIO和cStringIO已经被删除,现在应该使用StringIO进行导入:

from io import StringIO

为了支持两个版本:

try:
   from StringIO import StringIO
except ImportError:
   from io import StringIO

17
这就是答案。以下是问题内容:「如何使用boto3将字符串保存到S3对象中?」 - jkdev
对于Python3,我必须使用import io; fake_handle = io.StringIO(contents)。 - Felix

25
# Preface: File is json with contents: {'name': 'Android', 'status': 'ERROR'}

import boto3
import io

s3 = boto3.resource('s3')

obj = s3.Object('my-bucket', 'key-to-file.json')
data = io.BytesIO()
obj.download_fileobj(data)

# object is now a bytes string, Converting it to a dict:
new_dict = json.loads(data.getvalue().decode("utf-8"))

print(new_dict['status']) 
# Should print "Error"

16
永远不要将AWS_ACCESS_KEY_ID或AWS_SECRET_ACCESS_KEY放入您的代码中。应使用awscli的'aws configure'命令定义它们,它们将被botocore自动找到。 - Miles Erickson

5

注意:我假设您已经单独配置了身份验证。下面的代码是用于从S3存储桶下载单个对象。

import boto3

#initiate s3 client 
s3 = boto3.resource('s3')

#Download object to the file    
s3.Bucket('mybucket').download_file('hello.txt', '/tmp/hello.txt')

这段代码无法从s3文件夹内部下载,有没有办法使用这种方式来实现? - Marilu

5
如果您想下载文件的某个版本,您需要使用 get_object
import boto3

bucket = 'bucketName'
prefix = 'path/to/file/'
filename = 'fileName.ext'

s3c = boto3.client('s3')
s3r = boto3.resource('s3')

if __name__ == '__main__':
    for version in s3r.Bucket(bucket).object_versions.filter(Prefix=prefix + filename):
        file = version.get()
        version_id = file.get('VersionId')
        obj = s3c.get_object(
            Bucket=bucket,
            Key=prefix + filename,
            VersionId=version_id,
        )
        with open(f"{filename}.{version_id}", 'wb') as f:
            for chunk in obj['Body'].iter_chunks(chunk_size=4096):
                f.write(chunk)

参考:https://botocore.amazonaws.com/v1/documentation/api/latest/reference/response.html

(该文档为Amazon Web Services Botocore响应对象的参考文档,Botocore是AWS的低级别核心库之一)

4

当你想要使用不同于默认配置的配置来读取文件时,可以直接使用mpu.aws.s3_download(s3path, destination)或复制粘贴以下代码:

def s3_download(source, destination,
                exists_strategy='raise',
                profile_name=None):
    """
    Copy a file from an S3 source to a local destination.

    Parameters
    ----------
    source : str
        Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar'
    destination : str
    exists_strategy : {'raise', 'replace', 'abort'}
        What is done when the destination already exists?
    profile_name : str, optional
        AWS profile

    Raises
    ------
    botocore.exceptions.NoCredentialsError
        Botocore is not able to find your credentials. Either specify
        profile_name or add the environment variables AWS_ACCESS_KEY_ID,
        AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN.
        See https://boto3.readthedocs.io/en/latest/guide/configuration.html
    """
    exists_strategies = ['raise', 'replace', 'abort']
    if exists_strategy not in exists_strategies:
        raise ValueError('exists_strategy \'{}\' is not in {}'
                         .format(exists_strategy, exists_strategies))
    session = boto3.Session(profile_name=profile_name)
    s3 = session.resource('s3')
    bucket_name, key = _s3_path_split(source)
    if os.path.isfile(destination):
        if exists_strategy is 'raise':
            raise RuntimeError('File \'{}\' already exists.'
                               .format(destination))
        elif exists_strategy is 'abort':
            return
    s3.Bucket(bucket_name).download_file(key, destination)

from collections import namedtuple

S3Path = namedtuple("S3Path", ["bucket_name", "key"])


def _s3_path_split(s3_path):
    """
    Split an S3 path into bucket and key.

    Parameters
    ----------
    s3_path : str

    Returns
    -------
    splitted : (str, str)
        (bucket, key)

    Examples
    --------
    >>> _s3_path_split('s3://my-bucket/foo/bar.jpg')
    S3Path(bucket_name='my-bucket', key='foo/bar.jpg')
    """
    if not s3_path.startswith("s3://"):
        raise ValueError(
            "s3_path is expected to start with 's3://', " "but was {}"
            .format(s3_path)
        )
    bucket_key = s3_path[len("s3://"):]
    bucket_name, key = bucket_key.split("/", 1)
    return S3Path(bucket_name, key)

无法工作。NameError: name '_s3_path_split' is not defined - Dave Liu
@DaveLiu 谢谢你的提示,我已经调整了代码。不过在此之前这个包应该是可以工作的。 - Martin Thoma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接