Change controller to return file
continuous-integration/drone/push Build is passing
Details
continuous-integration/drone/push Build is passing
Details
This commit is contained in:
parent
670ddda93a
commit
3977c7896f
|
@ -4,5 +4,5 @@ images:
|
|||
access_key: ${ACCESS_KEY}
|
||||
secret_key: ${SECRET_KEY}
|
||||
endpoint: s3.clortox.com
|
||||
bucket: static-assets
|
||||
bucket: backgrounds
|
||||
secure: True
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
from fastapi import APIRouter, Depends, HTTPException, Header
|
||||
from fastapi import APIRouter, Depends, HTTPException, Header, BackgroundTasks
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from typing import List, Optional
|
||||
from pydantic import BaseModel
|
||||
|
@ -9,6 +10,7 @@ from minio import Minio
|
|||
import random
|
||||
import tempfile
|
||||
import traceback
|
||||
import os
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/images",
|
||||
|
@ -17,7 +19,7 @@ router = APIRouter(
|
|||
)
|
||||
|
||||
@router.get("/background/random")
|
||||
async def background(accept: str = Header(None)):
|
||||
async def background(background_tasks: BackgroundTasks):
|
||||
"""
|
||||
Will obtain a random image from the configured S3 bucket.
|
||||
"""
|
||||
|
@ -42,16 +44,15 @@ async def background(accept: str = Header(None)):
|
|||
|
||||
random_object_name = random.choice(object_names)
|
||||
print(random_object_name)
|
||||
scheme = "https" if secure else "http"
|
||||
object_url = f"{scheme}://{endpoint}/{bucket}/{random_object_name}"
|
||||
|
||||
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
||||
client.fget_object(bucket, random_object_name, temp_file.name)
|
||||
temp_file_name = temp_file.name
|
||||
|
||||
if accept and "image/" in accept:
|
||||
with tempfile.NamedTemporaryFile(detel=True) as temp_file:
|
||||
client.fget_object(bucket, random_object_name, temp_file)
|
||||
return FileResponse(temp_file.name, headers={"Content-Disposition": f"attachment; filename={random_object_name}"})
|
||||
background_tasks.add_task(delete_temp_file, temp_file_name)
|
||||
|
||||
return FileResponse(temp_file_name)
|
||||
|
||||
return object_url
|
||||
|
||||
|
||||
except Exception as err:
|
||||
|
@ -59,4 +60,9 @@ async def background(accept: str = Header(None)):
|
|||
raise HTTPException(status_code=500, detail=f"Unknown error. Check logs {err}")
|
||||
print(f"Error occurued processing background {err}")
|
||||
|
||||
# TODO get a sync up background
|
||||
def delete_temp_file(path: str):
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception as e:
|
||||
print(f"Error deleting file {path} : {e}")
|
||||
|
||||
|
|
Loading…
Reference in New Issue