[python] Boto3을 사용하여 S3 객체를 문자열로 열기

Boto 2를 사용하면 S3 객체를 다음과 같은 문자열로 열 수 있습니다. get_contents_as_string()

boto3에 동등한 기능이 있습니까?



답변

read바이트를 반환합니다. 적어도 Python 3의 경우 문자열을 반환하려면 올바른 인코딩을 사용하여 디코딩해야합니다.

import boto3

s3 = boto3.resource('s3')

obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8') 


답변

.get()AWS Lambda에서 Python 2.7 을 사용 했기 때문에 S3에서 객체를 읽거나 구문 분석하는 데 문제가있었습니다 .

예제에 json을 추가하여 구문 분석 가능하게 표시했습니다. 🙂

import boto3
import json

s3 = boto3.client('s3')

obj = s3.get_object(Bucket=bucket, Key=key)
j = json.loads(obj['Body'].read())

참고 (파이썬 2.7의 경우) : 내 객체는 모두 ASCII이므로 필요하지 않습니다. .decode('utf-8')

참고 (파이썬 3.6 이상) : 우리는 파이썬 3.6으로 옮겼으며 read()이제 bytes문자열을 가져 오려면 다음을 사용해야 한다는 것을 발견했습니다 .

j = json.loads(obj['Body'].read().decode('utf-8'))


답변

이것은 boto3 문서에 없습니다. 이것은 나를 위해 일했다 :

object.get()["Body"].read()

s3 객체 인 객체 : http://boto3.readthedocs.org/en/latest/reference/services/s3.html#object


답변

Python3 + boto3 API 접근법 사용.

S3.Client.download_fileobj APIPython 파일 유사 객체 를 사용하여 S3 객체 컨텐츠를 메모리로 검색 할 수 있습니다.

검색된 컨텐츠는 바이트이므로 str 로 변환 하려면이를 디코딩해야합니다.

import io
import boto3

client = boto3.client('s3')
bytes_buffer = io.BytesIO()
client.download_fileobj(Bucket=bucket_name, Key=object_key, Fileobj=bytes_buffer)
byte_value = bytes_buffer.getvalue()
str_value = byte_value.decode() #python3, default decoding is utf-8


답변

body에 io.StringIO가 포함 된 경우 다음과 같이해야합니다.

object.get()['Body'].getvalue()


답변