본문 바로가기
파이썬

파이썬 boto3를 사용하여 S3 객체를 파일에 저장하는 방법

by º기록 2020. 11. 25.
반응형


사용 사례는 매우 간단합니다. S3에서 객체를 가져와 파일에 저장합니다.

boto 2.X에서는 다음과 같이합니다.

import boto
key = boto.connect_s3().get_bucket('foo').get_key('foo')
key.get_contents_to_filename('/tmp/foo')

boto 3. 동일한 작업을 수행하는 깨끗한 방법을 찾을 수 없으므로 "Streaming"개체를 수동으로 반복하고 있습니다.

import boto3
key = boto3.resource('s3').Object('fooo', 'docker/my-image.tar.gz').get()
with open('/tmp/my-image.tar.gz', 'w') as f:
    chunk = key['Body'].read(1024*8)
    while chunk:
        f.write(chunk)
        chunk = key['Body'].read(1024*8)

또는

import boto3
key = boto3.resource('s3').Object('fooo', 'docker/my-image.tar.gz').get()
with open('/tmp/my-image.tar.gz', 'w') as f:
    for chunk in iter(lambda: key['Body'].read(4096), b''):
        f.write(chunk)

그리고 잘 작동합니다. 동일한 작업을 수행 할 "기본"boto3 함수가 있는지 궁금합니다.

 

해결 방법

 

최근에 Boto3에 들어간 사용자 지정 기능이 있습니다. 현재 하위 수준 S3 클라이언트에 노출되어 있으며 다음과 같이 사용할 수 있습니다.

s3_client = boto3.client('s3')
open('hello.txt').write('Hello, world!')

# Upload the file to S3
s3_client.upload_file('hello.txt', 'MyBucket', 'hello-remote.txt')

# Download the file from S3
s3_client.download_file('MyBucket', 'hello-remote.txt', 'hello2.txt')
print(open('hello2.txt').read())

이러한 기능은 파일 읽기 / 쓰기를 자동으로 처리하고 대용량 파일에 대해 멀티 파트 업로드를 병렬로 수행합니다.

s3_client.download_file 은 디렉토리를 생성하지 않습니다. pathlib.Path ( '/ path / to / file.txt'). parent.mkdir (parents = True, exist_ok = True) 로 생성 할 수 있습니다.

 

참조 페이지 https://stackoverflow.com/questions/29378763

 

 

반응형

댓글