[AWS] S3 API
포스트
취소

[AWS] S3 API

AWS SDK인 boto3의 S3와 관련된 주요 메서드를 알아 보겠습니다.

공통

botocore.config를 통해 AWS 클라이언트를 구성할 때 재시도 정책, 타임아웃, 지역 등의 다양한 설정을 지정할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
from botocore.config import Config as BotoConfig

config = BotoConfig(
    region_name='ap-northeast-2',
    retries={
        'max_attempts': 10,
        'mode': 'standard'
    },
    connect_timeout=5,
    read_timeout=60
)

s3.list_objects_v2()

list_objects_v2는 S3 버킷 안의 객체(파일) 목록을 가져오는 데 사용하는 메서드입니다.

지정한 Bucket과 Prefix에 존재하는 객체는 response의 Contents.Key에서 확인할 수 있습니다. ContinuationToken이나 페이징 처리를 하지 않은 경우 최대 1000개의 객체 목록을 가져옵니다.

1
2
3
4
5
6
7
8
9
10
11
12
import boto3

s3 = boto3.client('s3', config=config)

response = s3.list_objects_v2(
    Bucket=s3_bucket_name,
    Prefix=s3_prefix,
    MaxKeys=1000
)

for obj in response.get('Contents', []):
    print(obj['Key'])

s3.put_objects()

s3.put_objects는 S3에 객체(파일 등)를 업로드할 때 사용하는 메서드입니다.

1
2
3
4
5
6
7
8
9
10
11
import json
import boto3

s3 = boto3.client('s3', config=config)

s3.put_object(
    Bucket=s3_bucket_name,
    Key='prefix/object.json',
    Body=json.dumps({"key1": "value1"}),
    ContentType='application/json'
)

s3.delete_objects()

s3.delete_objects는 한 번에 여러 S3 객체를 삭제할 때 사용하는 메서드입니다. 최대 1000개의 객체까지 한 번에 삭제할 수 있습니다.

삭제할 객체들은 Delete.Objects에 key-value의 list로 정의할 수 있습니다. 존재하지 않는 Key는 삭제해도 오류 없이 성공한 것처럼 처리됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import boto3

s3 = boto3.client('s3', config=config)

response = s3.delete_objects(
    Bucket=s3_bucket_name,
    Delete={
        'Objects': [
            {'Key': 'prefix/object1.txt'},
            {'Key': 'prefix/object2.csv'},
        ],
        'Quiet': False 
    }
)
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.