如何在"boto3.client('s3').upload_fileobj()"中设置"--预期大小"选项?



由于能够在aws s3 cp中设置参数--expected-size,以确保成功上传大于5GB的文件/数据,因此如何在python版本中设置:boto3upload_filobj?

我试图将数据库备份作为数据流上传到S3,而不将其保存到磁盘,但由于InvalidArgument: Part number must be an integer between 1 and 10000, inclusive,它在过程中失败了。

我认为这是因为数据流是不可查找的,所以您必须明确设置预期的数据大小。

AWS CLI示例:

innobackupex --stream=xbstream --compress /backup 
| aws s3 cp - s3://backups/backup2018112 --expected-size=1099511627776

Boto3示例:

import subprocess
import boto3
innobackupexProc = subprocess.Popen([
'innobackupex',
'--stream=xbstream',
'--compress',
'/backup'
], stdout=subprocess.PIPE)
s3 = boto3.client('s3')
with innobackupexProc.stdout as dataStream:
s3.upload_fileobj(dataStream, 'backups', 'backup2018112')

错误是由于upload_fileobj使用了默认的8 MiB零件尺寸。示例CLI代码中的文件为1099511627776个字节,使用默认的部件大小(8388608个字节(,会产生131072个部件,远远超过Amazon S3多部件上传的最大10000个部件。

最大零件大小为5 GiB,因此,只要你的文件小于S3的最大对象大小5 TiB,你就可以将你的总文件大小除以10000(四舍五入(,得到一个有效的零件大小。在您的示例中,这将是109951163个字节,大约是105MiB。

然后,您可以通过upload_fileobjConfig参数设置多部分上传的部分大小:

import subprocess
import boto3
from boto3.s3.transfer import TransferConfig
# Amazon S3's maximum number of parts for multipart upload
MAX_PARTS = 10000
innobackupexProc = subprocess.Popen([
'innobackupex',
'--stream=xbstream',
'--compress',
'/backup'
], stdout=subprocess.PIPE)
# Assuming expected_size holds the expected number of bytes.
# Just do integer division and add 1, rather than converting
# to floats and using math.ceil - it doesn't matter if the 
# result is one greater than it should be!
# Note - Python 3 changed how / works, so you'll need to use //
part_size = (expected_size / MAX_PARTS) + 1
config = TransferConfig(multipart_chunksize=part_size)
s3 = boto3.client('s3')
with innobackupexProc.stdout as dataStream:
s3.upload_fileobj(dataStream, 'backups', 'backup2018112', Config=config)

最新更新