58 lines
No EOL
1.9 KiB
Python
58 lines
No EOL
1.9 KiB
Python
import os
|
|
from typing import Annotated
|
|
|
|
from fastapi import APIRouter, Depends, UploadFile
|
|
from starlette.responses import FileResponse
|
|
|
|
from authentication import get_current_active_user
|
|
from models import User
|
|
|
|
router = APIRouter()
|
|
|
|
@router.get("/")
|
|
async def get_images(current_user: Annotated[User, Depends(get_current_active_user)]):
|
|
# list all files in resources/images
|
|
files = [f for f in os.listdir("../resources/images") if os.path.isfile(os.path.join("../resources/images", f))]
|
|
# sort the files
|
|
files.sort()
|
|
return {"images": files}
|
|
|
|
@router.get("/{nom_image}")
|
|
async def get_image(nom_image: str, current_user: Annotated[User, Depends(get_current_active_user)]):
|
|
return FileResponse(f"./resources/images/{nom_image}")
|
|
|
|
@router.post("/")
|
|
async def ajouter_image(file: UploadFile, current_user: Annotated[User, Depends(get_current_active_user)]):
|
|
"""
|
|
Add an image to the images folder.
|
|
:param current_user:
|
|
:param file:
|
|
:return:
|
|
"""
|
|
image_path = f"{os.getcwd()}/resources/images/{file.filename}"
|
|
try:
|
|
contents = file.file.read()
|
|
with open(image_path, 'wb') as f:
|
|
f.write(contents)
|
|
except Exception as e:
|
|
return {"message": f"There was an error uploading the file: {e}"}
|
|
finally:
|
|
file.file.close()
|
|
|
|
return {"message": f"Successfully uploaded all files"}
|
|
|
|
@router.delete("/{nom_image}")
|
|
async def supprimer_image(nom_image: str, current_user: Annotated[User, Depends(get_current_active_user)]):
|
|
"""
|
|
Delete an image from the images folder.
|
|
:param current_user:
|
|
:param nom_image:
|
|
:return:
|
|
"""
|
|
image_path = f"{os.getcwd()}/resources/images/{nom_image}"
|
|
try:
|
|
os.remove(image_path)
|
|
except Exception as e:
|
|
return {"message": f"There was an error deleting the file: {e}"}
|
|
finally:
|
|
return {"message": f"Successfully deleted {nom_image}"} |