From 47ac48e563ce4f53be0344cb905c10088036166b Mon Sep 17 00:00:00 2001 From: Philip Cheung Date: Tue, 8 Oct 2024 10:22:05 +0800 Subject: [PATCH] delete image --- backend/app/utils.py | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/backend/app/utils.py b/backend/app/utils.py index 21fb610..468266f 100644 --- a/backend/app/utils.py +++ b/backend/app/utils.py @@ -18,6 +18,14 @@ from app.core.config import settings static = "static" +ConnectionUrl = f"https://{settings.AccountID}.r2.cloudflarestorage.com" + +r2 = boto3.client( + "s3", + endpoint_url=ConnectionUrl, + aws_access_key_id=settings.access_key_id, + aws_secret_access_key=settings.secret_access_key, + ) @dataclass class EmailData: @@ -195,13 +203,7 @@ def validate_file_size_type(file: IO): def upload_file(file_name, bucket_name, object_name=None): - ConnectionUrl = f"https://{settings.AccountID}.r2.cloudflarestorage.com" - r2 = boto3.client( - "s3", - endpoint_url=ConnectionUrl, - aws_access_key_id=settings.access_key_id, - aws_secret_access_key=settings.secret_access_key, - ) + if object_name is None: object_name = file_name @@ -213,6 +215,15 @@ def upload_file(file_name, bucket_name, object_name=None): return False return True +def delete_file(file_name, bucket_name, object_name=None): + if object_name is None: + object_name = file_name + try: + r2.delete_object(Bucket=bucket_name, Key=object_name) + except ClientError as e: + print(f"An error occurred: {e}") + return False + async def save_picture(file, folder_name: str = "", file_name: str = None): randon_uid = str(uuid4()) @@ -244,6 +255,7 @@ async def save_picture(file, folder_name: str = "", file_name: str = None): async def del_picture(picture_path): try: os.remove(picture_path) + delete_file(picture_path, "images") except Exception as e: print("Error: ", e) return False