implement S3 garage on the backend
This commit is contained in:
1 parent
4786c625c1
commit
830b4c7d4e
1 file changed
+15
-5
@@ -1,16 +1,20 @@
|
|||||||
|
from urllib.parse import unquote
|
||||||
from botocore.exceptions import ClientError
|
from botocore.exceptions import ClientError
|
||||||
from fastapi import APIRouter, HTTPException
|
from fastapi import APIRouter, HTTPException
|
||||||
from fastapi.responses import StreamingResponse
|
from fastapi.responses import StreamingResponse
|
||||||
|
|
||||||
from app.s3 import BUCKET_NAME, s3_client
|
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}")
|
@router.get("/{file_path:path}")
|
||||||
async def get_media(file_path: str):
|
async def get_media(file_path: str):
|
||||||
|
decoded_path = unquote(file_path)
|
||||||
|
clean_key = decoded_path.lstrip("/")
|
||||||
|
|
||||||
try:
|
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(
|
return StreamingResponse(
|
||||||
content=s3_object["Body"].iter_chunks(),
|
content=s3_object["Body"].iter_chunks(),
|
||||||
@@ -18,6 +22,12 @@ async def get_media(file_path: str):
|
|||||||
headers={"Cache-Control": "public, max-age=86400"},
|
headers={"Cache-Control": "public, max-age=86400"},
|
||||||
)
|
)
|
||||||
except ClientError as e:
|
except ClientError as e:
|
||||||
if e.response["Error"]["Code"] in ["NoSuchKey", "404"]:
|
error_code = e.response["Error"]["Code"]
|
||||||
raise HTTPException(status_code=404, detail="Fichier introuvable")
|
if error_code in ["NoSuchKey", "404"]:
|
||||||
raise HTTPException(status_code=500, detail="Erreur serveur S3")
|
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)}"
|
||||||
|
)
|
||||||
Reference in new issue
Block a user