CURD Operation on Amazon S3 Bucket

CURD Operation on Amazon S3 Bucket

Introduction

Amazon Simple Storage Service (S3) is one such prominent cloud storage service offered by Amazon Web Services (AWS). In this article, we will explore how to streamline your AWS S3 operations using the Python programming language and the Boto3 library. We'll cover the creation, uploading, deletion of files, as well as the creation and deletion of S3 buckets.

No alt text provided for this image
S3 Interface



Step-by-Step explanations

Getting Started: Setting Up Boto3 and AWS Credentials

  • Install the Boto3 library using pip install boto3.
  • Configure your AWS credentials using environment variables or aws configure in the AWS CLI.

pip install boto3        

  • Import boto3 library to allows you to directly create, update, and delete AWS resources from your Python scripts

import boto3        



Creating an S3 Bucket

  1. import Boto3 Library: Import the Boto3 library in your Python script to interact with AWS services programmatically.
  2. Initialize S3 Client: Use the boto3.client('s3') method to create an S3 client that enables communication with the S3 service.
  3. Call create_S3_bucket function: Utilize the s3.create_bucket() method with the Bucket parameter set to the desired bucket name.
  4. Handle Exceptions: Implement error handling to catch potential exceptions that might occur during the bucket creation process. This ensures graceful error messages are displayed to users.
  5. Success Message: Upon successful creation, print a success message indicating that the S3 bucket has been created, along with the bucket name and region.


Python Code

def create_s3_bucket(bucket_name, region='us-east-1'):
? ? try:
? ? ? ? s3 = boto3.client('s3', region_name=region)
? ? ? ? s3.create_bucket(Bucket=bucket_name)
? ? ? ? print(f"S3 bucket '{bucket_name}' created successfully in region '{region}'.")
? ? ? ? return bucket_name
? ? except Exception as e:
? ? ? ? print(f"An error occurred while creating the S3 bucket: {e}")
? ? ? ? return None
bucket_name = input("your-bucket-name")
region = 'us-east-1'
created_bucket = create_s3_bucket(bucket_name, region)        


Output

No alt text provided for this image
Response


No alt text provided for this image
hackmefornow12456 created successfully



Uploading a File to an S3 Bucket

  1. S3 Upload: This process involves sending a file from a local machine to an Amazon S3 bucket.
  2. Python Script: A Python script with the Boto3 library is used to manage the upload.
  3. Input: Users input the S3 bucket name, local file path, and a desired S3 key (object name).
  4. Boto3 Function: The script uses s3.upload_file() to send the file to the specified bucket with the provided S3 key.
  5. Outcome: The script provides clear feedback on success or failure of the upload process.


Python Code

def upload_file_to_s3(file_path, bucket_name, s3_key):
? ? try:
? ? ? ? s3 = boto3.client('s3')
? ? ? ? s3.upload_file(file_path, bucket_name, s3_key)
? ? ? ? print(f"File '{file_path}' uploaded to S3 bucket '{bucket_name}' with key '{s3_key}'.")
? ? ? ? return True
? ? except Exception as e:
? ? ? ? print(f"An error occurred while uploading the file: {e}")
? ? ? ? return False
bucket_name = input('your-bucket-name:')
local_file_path = input('Path of local file:')
s3_file_key = input('File name:')
upload_file_to_s3(local_file_path, bucket_name, s3_file_key)        


Output

No alt text provided for this image
Reponse


No alt text provided for this image
File upload successfully



Deleting a File from an S3 Bucket

  1. S3 File Deletion: This process involves removing a file from an Amazon S3 bucket, effectively deleting it.
  2. Python Script: The task is accomplished using a Python script powered by the Boto3 library for AWS interactions.
  3. Input: Users provide the S3 bucket name and the specific file key (object name) to be deleted.
  4. Boto3 Method: The script utilizes s3.delete_object() to initiate the deletion of the specified file from the given bucket.
  5. Feedback: The script offers clear feedback on whether the deletion was successful or if any errors occurred.


Python Code

def delete_file_from_s3(bucket_name, s3_key):
? ? try:
? ? ? ? s3 = boto3.client('s3')
? ? ? ? s3.delete_object(Bucket=bucket_name, Key=s3_key)
? ? ? ? print(f"File '{s3_key}' deleted from S3 bucket '{bucket_name}'.")
? ? ? ? return True
? ? except Exception as e:
? ? ? ? print(f"An error occurred while deleting the file: {e}")
? ? ? ? return False
bucket_name = input('your-bucket-name')
s3_file_key = input('Enter file-key name')
delete_file_from_s3(bucket_name, s3_file_key)        


Output

No alt text provided for this image
Response


No alt text provided for this image
File deleted sucessfully



Deleting an S3 Bucket

  1. S3 Bucket Deletion: This process involves removing an entire Amazon S3 bucket, including all its stored objects.
  2. Python Script: The task is accomplished using a Python script utilizing the Boto3 library for AWS interactions.
  3. Input: Users provide the name of the S3 bucket they want to delete.
  4. Boto3 Method: The script uses s3.delete_bucket() to initiate the removal of the specified S3 bucket.
  5. Confirmation: The script provides feedback to confirm whether the bucket was successfully deleted or if any errors were encountered.


Python Code

def delete_s3_bucket(bucket_name):
? ? try:
? ? ? ? s3 = boto3.client('s3')
? ? ? ? s3.delete_bucket(Bucket=bucket_name)
? ? ? ? print(f"S3 bucket '{bucket_name}' deleted successfully.")
? ? ? ? return True
? ? except Exception as e:
? ? ? ? print(f"An error occurred while deleting the S3 bucket: {e}")
? ? ? ? return False
bucket_name = input('your-bucket-name')
delete_s3_bucket(bucket_name)        


Output

No alt text provided for this image
Response


No alt text provided for this image
Bucket deleted successfully




Conclusion

  • AWS S3 Interaction: Explored using Python and Boto3, simplifying interaction with AWS S3 services.
  • Step-by-Step Approach: Process broken down into clear steps, covering bucket creation, file upload, and deletion.
  • Seamless Integration: Code snippets provided for developers to seamlessly integrate S3 functionalities into their applications.
  • Enhanced Data Management: Empowers developers and enthusiasts to efficiently manage cloud-based data using Python.
  • Continuous Exploration: Just the beginning—encouraged to delve deeper, discovering advanced features in cloud computing with Boto3 and AWS.




Feedback/Queries

I hope this article will be useful for you and that you learned something new Please, feel free to drop any questions in the comments below. I would be happy to answer them.

Thanks for reading???






Aditya Shrivastawa

C.Sc. Student || Devops || Data Analysis || Python || C++ || JAVA || BRLPS CBO's Accountant, Bihar Govt.|| Technical Writer

1 年

Bahut mehnat kar rahe Hain aap log ????????

要查看或添加评论,请登录

社区洞察

其他会员也浏览了