Como fazer upload de string como objeto Wasabi/S3 usando boto3 em Python

Para fazer upload de uma string Python como

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

para um armazenamento compatível com S3 como Wasabi ou Amazon S3, você precisa codificá-la usando .encode("utf-8") e então envolvê-la em um objeto io.BytesIO:

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

Exemplo completo:

upload_string_full_example.py
import boto3
import io

# Criar conexão com 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'
)

# Obter objeto bucket
my_bucket = s3.Bucket('boto-test')

# Enviar string para arquivo
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")

Não se esqueça de preencher MY_ACCESS_KEY e MY_SECRET_KEY. Dependendo de qual região e qual serviço compatível com S3 você usa, pode ser necessário usar outra URL de endpoint em vez de https://s3.eu-central-1.wasabisys.com.


Check out similar posts by category: Python S3