delete image

This commit is contained in:
Philip Cheung 2024-10-08 10:22:05 +08:00
parent 5a5f588274
commit 47ac48e563
1 changed files with 19 additions and 7 deletions

View File

@ -18,6 +18,14 @@ from app.core.config import settings
static = "static" 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 @dataclass
class EmailData: class EmailData:
@ -195,13 +203,7 @@ def validate_file_size_type(file: IO):
def upload_file(file_name, bucket_name, object_name=None): 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: if object_name is None:
object_name = file_name object_name = file_name
@ -213,6 +215,15 @@ def upload_file(file_name, bucket_name, object_name=None):
return False return False
return True 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): async def save_picture(file, folder_name: str = "", file_name: str = None):
randon_uid = str(uuid4()) 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): async def del_picture(picture_path):
try: try:
os.remove(picture_path) os.remove(picture_path)
delete_file(picture_path, "images")
except Exception as e: except Exception as e:
print("Error: ", e) print("Error: ", e)
return False return False