implement S3 garage on the backend

This commit is contained in:
Giovanni committed 2026-10-05 21:42:40 +02:00
1 parent 4786c625c1
commit 830b4c7d4e
1 file changed
+15 -5
+15 -5
View File
@@ -1,16 +1,20 @@
from urllib.parse import unquote
from botocore.exceptions import ClientError
from fastapi import APIRouter, HTTPException
from fastapi.responses import StreamingResponse
from app.s3 import BUCKET_NAME, s3_client
router = APIRouter(prefix="/media", tags=["Media"])
router = APIRouter(prefix="/media", tags=["media"])
@router.get("/{file_path:path}")
async def get_media(file_path: str):
decoded_path = unquote(file_path)
clean_key = decoded_path.lstrip("/")
try:
s3_object = s3_client.get_object(Bucket=BUCKET_NAME, Key=file_path)
s3_object = s3_client.get_object(Bucket=BUCKET_NAME, Key=clean_key)
return StreamingResponse(
content=s3_object["Body"].iter_chunks(),
@@ -18,6 +22,12 @@ async def get_media(file_path: str):
headers={"Cache-Control": "public, max-age=86400"},
)
except ClientError as e:
if e.response["Error"]["Code"] in ["NoSuchKey", "404"]:
raise HTTPException(status_code=404, detail="Fichier introuvable")
raise HTTPException(status_code=500, detail="Erreur serveur S3")
error_code = e.response["Error"]["Code"]
if error_code in ["NoSuchKey", "404"]:
raise HTTPException(
status_code=404,
detail=f"Fichier introuvable sur S3 pour la clé : '{clean_key}'",
)
raise HTTPException(
status_code=500, detail=f"Erreur serveur S3: {str(e)}"
)