programing

boto3를 사용하여 S3 객체에 파일 또는 데이터를 쓰는 방법

cafebook 2023. 7. 2. 20:57
반응형

boto3를 사용하여 S3 객체에 파일 또는 데이터를 쓰는 방법

boto 2에서는 다음 방법을 사용하여 S3 개체에 쓸 수 있습니다.

bot 3에 해당하는 것이 있습니까?S3에 저장된 객체에 데이터를 저장하는 boto3 방법은 무엇입니까?

bto 3에서 'Key.set_contents_from_' 메서드는 다음과 같이 대체되었습니다.

예:

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')

또는 bto 2와 bto 3을 비교하는 공식 문서에 설명된 바와 같이 바이너리 데이터는 파일을 읽음으로써 얻을 수 있습니다.

데이터 저장

파일, 스트림 또는 문자열의 데이터를 쉽게 저장할 수 있습니다.

# 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'))

boto3에는 파일을 직접 업로드하는 방법도 있습니다.

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

S3에서 파일에 쓰기 전에 더 이상 내용을 이진으로 변환할 필요가 없습니다.다음 예제에서는 문자열 내용이 포함된 S3 버킷에 새 텍스트 파일(newfile.txt)을 만듭니다.

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)

다음은 s3에서 JSON을 읽는 좋은 방법입니다.

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))

이제 사용할 수 있습니다.json.load_s3그리고.json.dump_s3와 동일한 API를 사용하여load그리고.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/key

주어진 S3 버킷 및 하위 폴더에 파일을 즉시 업로드할 때 사용하는 더 깨끗하고 간결한 버전.

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="")

메모항상 AWS 자격 증명을 입력해야 합니다(aws_access_key_id그리고.aws_secret_access_key) 별도의 파일로, 예를 들어 -~/.aws/credentials

몇 가지 조사 후에, 저는 이것을 발견했습니다.간단한 csv 기록기를 사용하여 수행할 수 있습니다.사전을 CSV에 직접 S3 버킷에 쓰는 것입니다.

예: 모든 사전의 키가 동일하다고 가정할 때 data_proxy = [{"Key1": "value1", "Key2": "value2", {"Key1": "value4", "Key2": "value3"}}.

import csv
import boto3

# Sample input dictionary
data_dict = [{"Key1": "value1", "Key2": "value2"}, {"Key1": "value4", "Key2": "value3"}]
data_dict_keys = data_dict[0].keys()

# creating a file buffer
file_buff = StringIO()
# writing csv data to file buffer
writer = csv.DictWriter(file_buff, fieldnames=data_dict_keys)
writer.writeheader()
for data in data_dict:
    writer.writerow(data)
# creating s3 client connection
client = boto3.client('s3')
# placing file to S3, file_buff.getvalue() is the CSV body for the file
client.put_object(Body=file_buff.getvalue(), Bucket='my_bucket_name', Key='my/key/including/anotherfilename.txt')

를 사용하는 스마트 오픈을 언급할 가치가 있습니다.boto3백엔드로

smart-open파이썬의 드롭인 대체품입니다.open에서 파일을 열 수 있습니다.s3,게다가ftp,http그리고 다른 많은 프로토콜들.

예를들면

from smart_open import open
import json
with open("s3://your_bucket/your_key.json", 'r') as f:
    data = json.load(f)

aws 자격 증명은 bot3 자격 증명(일반적으로 파일)을 통해 로드됩니다.~/.aws/dir 또는 환경 변수.

아래 코드를 사용하여 2019년 S3에 이미지를 작성할 수 있습니다.S3에 연결하려면 명령을 사용하여 AWS CLI를 설치해야 합니다.pip install awscli그런 다음 명령을 사용하여 자격 증명을 몇 개 입력합니다.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

언급URL : https://stackoverflow.com/questions/40336918/how-to-write-a-file-or-data-to-an-s3-object-using-boto3

반응형