如何在 Python 中使用 boto3 将字符串上传为 Wasabi/S3 对象

为了上传类似这样的 Python 字符串

upload_string_boto3_example.py
my_string = "This shall be the content for a file I want to create on an S3-compatible storage"

到 Wasabi 或 Amazon S3 等 S3 兼容存储,你需要使用 .encode("utf-8") 编码它,然后将其包装在 io.BytesIO 对象中:

upload_fileobj_snippet.py
my_bucket.upload_fileobj(io.BytesIO(my_string.encode("utf-8")), "myfile.txt")

完整示例:

upload_string_full_example.py
import boto3
import io

# 创建到 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 对象
my_bucket = s3.Bucket('boto-test')

# 将字符串上传到文件
my_string = "This shall be the content for a file I want to create on an S3-compatible storage"

my_bucket.upload_fileobj(io.BytesIO(my_string.encode("utf-8")), "myfile.txt")

Don’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 instead of https://s3.eu-central-1.wasabisys.com.


Check out similar posts by category: Python, S3