为了上传类似这样的 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")不要忘记填写 MY_ACCESS_KEY 和 MY_SECRET_KEY。根据你使用的区域和 S3 兼容服务,你可能需要使用另一个 endpoint URL 来代替 https://s3.eu-central-1.wasabisys.com。