Change controller to return file
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Tyler Perkins 2023-11-01 22:39:52 -04:00
parent 670ddda93a
commit 3977c7896f
2 changed files with 17 additions and 11 deletions

View File

@ -4,5 +4,5 @@ images:
access_key: ${ACCESS_KEY} access_key: ${ACCESS_KEY}
secret_key: ${SECRET_KEY} secret_key: ${SECRET_KEY}
endpoint: s3.clortox.com endpoint: s3.clortox.com
bucket: static-assets bucket: backgrounds
secure: True secure: True

View File

@ -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 typing import List, Optional
from pydantic import BaseModel from pydantic import BaseModel
@ -9,6 +10,7 @@ from minio import Minio
import random import random
import tempfile import tempfile
import traceback import traceback
import os
router = APIRouter( router = APIRouter(
prefix="/images", prefix="/images",
@ -17,7 +19,7 @@ router = APIRouter(
) )
@router.get("/background/random") @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. 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) random_object_name = random.choice(object_names)
print(random_object_name) 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: background_tasks.add_task(delete_temp_file, temp_file_name)
with tempfile.NamedTemporaryFile(detel=True) as temp_file:
client.fget_object(bucket, random_object_name, temp_file) return FileResponse(temp_file_name)
return FileResponse(temp_file.name, headers={"Content-Disposition": f"attachment; filename={random_object_name}"})
return object_url
except Exception as err: 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}") raise HTTPException(status_code=500, detail=f"Unknown error. Check logs {err}")
print(f"Error occurued processing background {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}")