From be53859af37699682155c302b04b5fc5604ffe6d Mon Sep 17 00:00:00 2001 From: "[esekyi]" <[sskert10@gmail.com]> Date: Tue, 27 Aug 2024 03:43:50 +0000 Subject: [PATCH] =?UTF-8?q?[Update=F0=9F=93=A2]=20Image=20service=20using?= =?UTF-8?q?=20boto3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/config.py | 17 ++++++++++---- app/services/image_service.py | 42 +++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 4 deletions(-) create mode 100644 app/services/image_service.py diff --git a/app/config.py b/app/config.py index e9f042f..5517cfa 100644 --- a/app/config.py +++ b/app/config.py @@ -1,11 +1,20 @@ import os from werkzeug.utils import secure_filename +from dotenv import load_dotenv + + +# loading environment variables from .env file +load_dotenv() class Config: - SECRET_KEY = os.environ.get('SECRET_KEY') or 'with_this_you-will-never-guess' - SQLALCHEMY_DATABASE_URI = os.environ.get( + SECRET_KEY = os.getenv('SECRET_KEY') or 'with_this_you-will-never-guess' + SQLALCHEMY_DATABASE_URI = os.getenv( 'DATABASE_URL') or 'postgresql://spiceshare:fudf2024@localhost/spiceshare_db' SQLALCHEMY_TRACK_MODIFICATIONS = False - UPLOAD_FOLDER = 'app/static/uploads' - ALLOWED_EXTENSIONS = {'jpg', 'jpeg', 'png', 'gif'} + # AWS S3 configuration + S3_BUCKET = os.getenv('S3_BUCKET_NAME') + S3_ACCESS_KEY = os.getenv('AWS_ACCESS_KEY_ID') + S3_SECRET_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') + S3_REGION = os.getenv('AWS_REGION', 'us-east-1') + S3_URL = f"https://{S3_BUCKET}.s3.amazonaws.com/" diff --git a/app/services/image_service.py b/app/services/image_service.py new file mode 100644 index 0000000..ebc53b6 --- /dev/null +++ b/app/services/image_service.py @@ -0,0 +1,42 @@ +import boto3 +from botocore.exceptions import NoCredentialsError, ClientError +from flask import current_app +import uuid +from werkzeug.utils import secure_filename + + +def upload_image_to_s3(image, folder='recipes'): + """Upload image to S3 bucket and retrieve the given image URL""" + try: + # Generating a random and unique filename for image + filename = secure_filename(image.filename) + unique_filename = f"{uuid.uuid4().hex}_{filename}" + + # Init the S3 client + s3_client = boto3.client( + 's3', + aws_access_key_id=current_app.config['S3_ACCESS_KEY'], + aws_secret_access_key=current_app.config['S3_SECRET_KEY'], + region_name=current_app.config['S3_REGION'] + ) + + # Upload the file to S3 + s3_client.upload_fileobj( + image, + current_app.config['S3_BUCKET'], + f"{folder}/{unique_filename}", + ExtraArgs={ + "ACL": "public-read", + "ContentType": image.content_type + } + ) + + # Return URL of uploaded image + image_url = f"{current_app.config['S3_URL']}{folder}/{unique_filename}" + return image_url + + + except NoCredentialsError: + raise ValueError("AWS credentials not available") + except ClientError as e: + raise ValueError(f"Failed to upload image: {e}")