Preparation
In
import json
from pprint import pp
import boto3
s3 = boto3.client("s3")
Create a bucket
In
response = s3.create_bucket(
Bucket="<bucket_name>",
CreateBucketConfiguration={"LocationConstraint": "<region>"},
)
pp(response)
Out
{'ResponseMetadata': {'RequestId': '45E82X1PFTJ448BX',
'HostId': '8gqIBKcd9l6hvE6cj6mm+wDEBNpwMUWkYam1Qd/CFINiQmNI7rqn+gY8/fnLpx53PjlRFjmU8u4=',
'HTTPStatusCode': 200,
'HTTPHeaders': {'x-amz-id-2': '8gqIBKcd9l6hvE6cj6mm+wDEBNpwMUWkYam1Qd/CFINiQmNI7rqn+gY8/fnLpx53PjlRFjmU8u4=',
'x-amz-request-id': '45E82X1PFTJ448BX',
'date': 'Wed, 29 Jun 2022 15:22:21 GMT',
'location': 'http://<bucket_name>.s3.amazonaws.com/',
'server': 'AmazonS3',
'content-length': '0'},
'RetryAttempts': 0},
'Location': 'http://<bucket_name>.s3.amazonaws.com/'}
Upload an object
In
response = s3.put_object(
Body=open("/tmp/test.txt", mode="rb").read(),
Bucket="<bucket_name>",
ContentType="text/plain",
Key="test.txt",
)
pp(response)
Out
{'ResponseMetadata': {'RequestId': 'KGDVN0Q8539K8ATR',
'HostId': 'Ij3RnIyhOtV9j2cUQ52gucTKroPVC1uo744jAyRy06itAbttcfjU8XChi3GpaqdD/IhhaOVqqiM=',
'HTTPStatusCode': 200,
'HTTPHeaders': {'x-amz-id-2': 'Ij3RnIyhOtV9j2cUQ52gucTKroPVC1uo744jAyRy06itAbttcfjU8XChi3GpaqdD/IhhaOVqqiM=',
'x-amz-request-id': 'KGDVN0Q8539K8ATR',
'date': 'Wed, 29 Jun 2022 15:34:44 GMT',
'etag': '"02bcabffffd16fe0fc250f08cad95e0c"',
'server': 'AmazonS3',
'content-length': '0'},
'RetryAttempts': 0},
'ETag': '"02bcabffffd16fe0fc250f08cad95e0c"'}
Download the object
In
response = s3.get_object(
Bucket="<bucket_name>",
Key="test.txt",
)
pp(response)
Out
{'ResponseMetadata': {'RequestId': 'VFRGAK3EBSGA1XGS',
'HostId': 'VBUkwBOKBD2OwD32lS+Dr6k5qZSpy4m5HS6Sr37VD07OioAy4FfBCsOn+Qs5FZB8gNYEkjnBlLo=',
'HTTPStatusCode': 200,
'HTTPHeaders': {'x-amz-id-2': 'VBUkwBOKBD2OwD32lS+Dr6k5qZSpy4m5HS6Sr37VD07OioAy4FfBCsOn+Qs5FZB8gNYEkjnBlLo=',
'x-amz-request-id': 'VFRGAK3EBSGA1XGS',
'date': 'Wed, 29 Jun 2022 15:34:49 GMT',
'last-modified': 'Wed, 29 Jun 2022 '
'15:34:44 GMT',
'etag': '"02bcabffffd16fe0fc250f08cad95e0c"',
'accept-ranges': 'bytes',
'content-type': 'text/plain',
'server': 'AmazonS3',
'content-length': '16'},
'RetryAttempts': 0},
'AcceptRanges': 'bytes',
'LastModified': datetime.datetime(2022, 6, 29, 15, 34, 44, tzinfo=tzutc()),
'ContentLength': 16,
'ETag': '"02bcabffffd16fe0fc250f08cad95e0c"',
'ContentType': 'text/plain',
'Metadata': {},
'Body': <botocore.response.StreamingBody object at 0x7fc60007b8e0>}
Read the object body
In
content = response["Body"].read().decode("utf-8")
print(content)
Out
This is a test.
Top comments (0)