我正在尝试用 new 做一个“hello world”boto3AWS 的客户端。
我的用例相当简单:从 S3 获取对象并将其保存到文件中。
在 boto 2.X 中我会这样做:
import boto
key = boto.connect_s3().get_bucket('foo').get_key('foo')
key.get_contents_to_filename('/tmp/foo')
在博托 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)
or
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 函数可以执行相同的任务?
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)
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)