In this post, I will show you
how to create S3 bucket,
how to put objects into the bucket,
how to upload multiple objects in s3,
how to download multiple objects,
how to control access policy, and
how to host a static website in S3.
1. How to create S3 Bucket using Python3 Boto3?
Object : resource method: create_bucket
important method parameters:
ACL : private or public
Bucket - name of the bucket name this should be unique for each bucket
CreateBucketConfiguration - have the LocationConstrating that is region on which you want to host your s3 bucket.
import boto3 s3_resource = boto3.resource('s3') bucket = s3_resource.create_bucket(ACL='private', Bucket='vybhava2023demo.com', CreateBucketConfiguration={ 'LocationConstrating': 'us-west-2' }) print("Successfully create bucket:", bucket)
2. How to put the objects into the S3 Bucket using Boto3
When you want to add file from local system we can use Python file methods and have a object reference here f is the reference to the file opened for read operation.
f=open('greet.txt').read() s3_client =boto3.client('s3') respose = s3_client.put_object( ACL='private', Body=f, Bucket='vybhava2023demo.com', Key='greet.txt' )
3. Delete object from S3 Bucket
Delete object from S3 bucketObject : client
method : delete_object()
s3_client = boto3.client('s3') response = s3_client.delete_object( Bucket='vybhava2023demo.com', Key='greet.txt' )
4. List all content objects in a Bucket
List all the contents of a Bucket this may be file objects those are put into the Bucket earlier.
Object: client
method: list_objects
s3_client = boto3.client('s3') response = s3_client.list_objects( Bucket='vybhava2023demo.com' ) for content in response['Contents']: print(content['Key'])
5. List all S3 Buckets
Get the s3_client objectmethod: list_buckets :
On the aws-cli run the command: aws s3 ls
# File: list-s3.py # Description: This script will list all s3 buckets using client interface s3_client = boto3.client('s3') list_buckets=s3_client.list_buckets() print(list_buckets) # run 2 for b in list_buckets['Buckets']: print(b['Name'])Hope you enjoyed this post!! Please write back your errors and exceptions when you run the Boto3 programs for AWS services and resources.