Programing

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

lottogame 2020. 11. 3. 07:36
반응형

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


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

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


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

또는 boto 2와 boto 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.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에서 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_s3json.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의 파일에 쓰기 전에 콘텐츠를 바이너리로 변환 할 필요가 없습니다. 다음 예제는 문자열 콘텐츠가있는 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 버킷 및 하위 폴더에 즉시 파일을 업로드하는 데 사용하는 깔끔하고 간결한 버전-

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_idaws_secret_access_key)을 별도의 파일에 넣어야합니다 . 예 :~/.aws/credentials


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

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

smart-open is a drop-in replacement for python's open that can open files from s3, as well as ftp, http and many other protocols.

for example

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

The aws credentials are loaded via boto3 credentials, usually a file in the ~/.aws/ dir or an environment variable.

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

반응형