如何使用 boto3 在 Wasabi / S3 中创建大量测试文件
以下示例代码在 Wasabi / S3 上创建 10000 个测试文件。它基于如何使用 concurrent.futures map 和 tqdm 进度条:
create_s3_test_files.py
import boto3
import concurrent.futures
executor = concurrent.futures.ThreadPoolExecutor(64)
from tqdm import tqdm
import concurrent.futures
def tqdm_parallel_map(executor, fn, *iterables, **kwargs):
"""
等同于 executor.map(fn, *iterables),
但显示基于 tqdm 的进度条。
不支持 timeout 或 chunksize,因为内部使用 executor.submit
**kwargs 传递给 tqdm。
"""
futures_list = []
for iterable in iterables:
futures_list += [executor.submit(fn, i) for i in iterable]
for f in tqdm(concurrent.futures.as_completed(futures_list), total=len(futures_list), **kwargs):
yield f.result()
# 创建到 Wasabi / S3 的连接
s3 = boto3.resource('s3',
endpoint_url = 'https://s3.eu-central-1.wasabisys.com',
aws_access_key_id = 'MY_ACCESS_KEY',
aws_secret_access_key = 'MY_SECRET_KEY'
)
# 获取 bucket 对象
boto_test_bucket = s3.Bucket('boto-test')
def create_s3_object(i, directory):
# 创建测试数据
buf = io.BytesIO()
buf.write(f"{i}".encode())
# 重置读取指针。不要忘记此步骤,否则所有上传的文件将为空!
buf.seek(0)
# 上传文件
boto_test_bucket.upload_fileobj(buf, f"{directory}/{i}.txt")
for _ in tqdm_parallel_map(executor, lambda i: create_s3_object(i, directory="10k-Test-Objects"), range(1, 10001)):
passDon’t forget to fill in MY_ACCESS_KEY and MY_SECRET_KEY. Depending on what region and what S3-compatible service you use, you might need to use another endpoint URL at https://s3.eu-central-1.wasabisys.com.
注意运行此脚本,特别是创建大量测试文件时,将向你的 S3 提供商发送大量请求,根据你使用的计划,这些请求可能很昂贵。例如,Wasabi 不收取请求费用但收取存储费用(在撰写本文时,每月最低收取 1TB 存储费用)。
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow