AWS S3 with Python

nelsonmendezz_

Nelson Hernández

Posted on February 3, 2022

AWS S3 with Python

In this example we will see the basic operations that we can do with the cube and the files

Installation

pip install boto3
Enter fullscreen mode Exit fullscreen mode

Connection

from boto3 import client
from os import getenv

clientS3 = client("s3",
                  aws_access_key_id=getenv("AWS_ACCESS_KEY_ID"),
                  aws_secret_access_key=getenv("AWS_SECRET_ACCESS_KEY"),
                  region_name=getenv("REGION_NAME")
                  )
Enter fullscreen mode Exit fullscreen mode

Methods for buckets

Create bucket

from botocore.exceptions import ClientError

def create_bucket(bucket: str):
    try:
        response = clientS3.create_bucket(Bucket=bucket)
        return response
    except ClientError as e:
        return e.response["Error"]
Enter fullscreen mode Exit fullscreen mode

Delete bucket

from botocore.exceptions import ClientError

def delete_bucket(bucket: str):
    try:
        response = clientS3.delete_bucket(Bucket=bucket)
        return response
    except ClientError as e:
        return e.response["Error"]
Enter fullscreen mode Exit fullscreen mode

List all buckets

from botocore.exceptions import ClientError

def list_buckets():
    try:
        response = clientS3.list_buckets()
        return response
    except ClientError as e:
        return e.response["Error"]
Enter fullscreen mode Exit fullscreen mode

Methods for files

Upload file

from typing import BinaryIO
from botocore.exceptions import ClientError

def upload_file(data: BinaryIO, bucket: str, filename: str):
    try:
        clientS3.upload_fileobj(Fileobj=data, Bucket=bucket, Key=filename)
        return "success"
    except ClientError as e:
        return e.response["Error"]
Enter fullscreen mode Exit fullscreen mode

Get file

from typing import BinaryIO
from botocore.exceptions import ClientError

def get_file(bucket: str, filename: str):
    try:
        response = clientS3.get_object(Bucket=bucket, Key=filename)
        return response
    except ClientError as e:
        return e.response["Error"]
Enter fullscreen mode Exit fullscreen mode

Delete file

from typing import BinaryIO
from botocore.exceptions import ClientError

def delete_file(bucket: str, filename: str):
    try:
        response = clientS3.delete_object(Bucket=bucket, Key=filename)
        return response
    except ClientError as e:
        return e.response["Error"]
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
nelsonmendezz_
Nelson Hernández

Posted on February 3, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

AWS S3 with Python
aws AWS S3 with Python

February 3, 2022