以下是一个使用 AWS SDK for Python(Boto3)的代码示例,演示如何将源存储桶中的对象复制到多个目标存储桶。
import boto3
def copy_object(source_bucket, source_key, target_buckets):
s3 = boto3.resource('s3')
for target_bucket in target_buckets:
# 构建目标对象的键(与源对象相同)
target_key = source_key
# 创建源对象的引用
source_obj = {
'Bucket': source_bucket,
'Key': source_key
}
# 创建目标对象的引用
target_obj = {
'Bucket': target_bucket,
'Key': target_key
}
# 复制对象
s3.meta.client.copy(source_obj, target_bucket, target_key)
print(f"已将对象从源存储桶 {source_bucket} 复制到目标存储桶 {target_bucket}")
# 定义源存储桶和目标存储桶列表
source_bucket = 'source-bucket'
target_buckets = ['target-bucket1', 'target-bucket2', 'target-bucket3']
# 定义源对象的键
source_key = 'path/to/source-object-key'
# 复制对象到多个目标存储桶
copy_object(source_bucket, source_key, target_buckets)
在上述代码示例中,我们首先导入 boto3
库并创建一个 S3 客户端。然后,我们使用 copy()
方法将源存储桶中的对象复制到每个目标存储桶。
请确保已安装 boto3
库,并使用有效的 AWS 凭证配置您的环境,以便访问源存储桶和目标存储桶。