En boto 2, puede escribir en un objeto S3 utilizando estos métodos:
¿Hay un boto 3 equivalente? ¿Cuál es el método boto3 para guardar datos en un objeto almacenado en S3?
Una versión más limpia y concisa que utilizo para cargar archivos sobre la marcha en un contenedor y una subcarpeta S3 determinados.
import boto3 BUCKET_NAME = 'sample_bucket_name' PREFIX = 'sub-folder/' s3 = boto3.resource('s3') # Creating an empty file called "_DONE" and putting it in the S3 bucket s3.Object(BUCKET_NAME, PREFIX + '_DONE').put(Body="") Nota : SIEMPRE debe colocar sus credenciales de AWS ( aws_access_key_id y aws_secret_access_key ) en un archivo separado, por ejemplo, ~/.aws/credentials
Ya no tiene que convertir el contenido a binario antes de escribir en el archivo en S3. El siguiente ejemplo crea un nuevo archivo de texto (llamado newfile.txt) en un depósito S3 con contenido de cadena:
import boto3 s3 = boto3.resource( 's3', region_name='us-east-1', aws_access_key_id=KEY_ID, aws_secret_access_key=ACCESS_KEY ) content="String content to write to a new S3 file" s3.Object('my-bucket-name', 'newfile.txt').put(Body=content)boto3 también tiene un método para cargar un archivo directamente:
s3 = boto3.resource('s3') s3.Bucket('bucketname').upload_file('/local/file/here.txt','folder/sub/path/to/s3key')http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.upload_file
Aquí hay un buen truco para leer JSON desde s3:
import json, boto3 s3 = boto3.resource("s3").Bucket("bucket") json.load_s3 = lambda f: json.load(s3.Object(key=f).get()["Body"]) json.dump_s3 = lambda obj, f: s3.Object(key=f).put(Body=json.dumps(obj)) Ahora puede usar json.load_s3 y json.dump_s3 con la misma API que load y dump
data = {"test":0} json.dump_s3(data, "key") # saves json to s3://bucket/key data = json.load_s3("key") # read json from s3://bucket/keyEn boto 3, los métodos 'Key.set_contents_from_' fueron reemplazados por
Por ejemplo:
import boto3 some_binary_data = b'Here we have some data' more_binary_data = b'Here we have some more data' # Method 1: Object.put() s3 = boto3.resource('s3') object = s3.Object('my_bucket_name', 'my/key/including/filename.txt') object.put(Body=some_binary_data) # Method 2: Client.put_object() client = boto3.client('s3') client.put_object(Body=more_binary_data, Bucket='my_bucket_name', Key='my/key/including/anotherfilename.txt')Alternativamente, los datos binarios pueden provenir de la lectura de un archivo, como se describe en los documentos oficiales que comparan boto 2 y boto 3 :
Almacenamiento de datos
Almacenar datos de un archivo, flujo o cadena es fácil:
# Boto 2.x from boto.s3.key import Key key = Key('hello.txt') key.set_contents_from_file('/tmp/hello.txt') # Boto 3 s3.Object('mybucket', 'hello.txt').put(Body=open('/tmp/hello.txt', 'rb'))
vale la pena mencionar smart-open que usa boto3 como back-end.
smart-open es un reemplazo directo de python's open que puede abrir archivos desde s3 , así como ftp , http y muchos otros protocolos.
por ejemplo
from smart_open import open import json with open("s3://your_bucket/your_key.json", 'r') as f: data = json.load(f) Las credenciales de aws se cargan mediante boto3 credentials , generalmente un archivo en el ~/.aws/ o una variable de entorno.
Puede usar el siguiente código para escribir, por ejemplo, una imagen en S3 en 2019. Para poder conectarse a S3, deberá instalar AWS CLI usando el comando pip install awscli , luego ingrese algunas credenciales usando el comando aws configure :
import urllib3 import uuid from pathlib import Path from io import BytesIO from errors import custom_exceptions as cex BUCKET_NAME = "xxx.yyy.zzz" POSTERS_BASE_PATH = "assets/wallcontent" CLOUDFRONT_BASE_URL = "https://xxx.cloudfront.net/" class S3(object): def __init__(self): self.client = boto3.client('s3') self.bucket_name = BUCKET_NAME self.posters_base_path = POSTERS_BASE_PATH def __download_image(self, url): manager = urllib3.PoolManager() try: res = manager.request('GET', url) except Exception: print("Could not download the image from URL: ", url) raise cex.ImageDownloadFailed return BytesIO(res.data) # any file-like object that implements read() def upload_image(self, url): try: image_file = self.__download_image(url) except cex.ImageDownloadFailed: raise cex.ImageUploadFailed extension = Path(url).suffix id = uuid.uuid1().hex + extension final_path = self.posters_base_path + "/" + id try: self.client.upload_fileobj(image_file, self.bucket_name, final_path ) except Exception: print("Image Upload Error for URL: ", url) raise cex.ImageUploadFailed return CLOUDFRONT_BASE_URL + id