下面的代码示例显示了如何使用 AWS SDK for Python (Boto3) 从目录桶中的对象读取数据。
import boto3
from botocore.exceptions import ClientError
from botocore.response import StreamingBody
def get_object(s3_client: boto3.client, bucket_name: str, key_name: str) -> StreamingBody:
"""
Gets the object.
:param s3_client:
:param bucket_name: The bucket that contains the object.
:param key_name: The key of the object to be downloaded.
:return: The object data in bytes.
"""
try:
response = s3_client.get_object(Bucket=bucket_name, Key=key_name)
body = response['Body'].read()
print(f"Got object '{key_name}' from bucket '{bucket_name}'.")
except ClientError:
print(f"Couldn't get object '{key_name}' from bucket '{bucket_name}'.")
raise
else:
return body
def main():
s3_client = boto3.client('s3')
resp = get_object(s3_client, 'doc-example-bucket
--use1-az4
--x-s3', 'sample.txt
')
print(resp)
if __name__ == "__main__":
main()