General-API/src/routers/images.py

63 lines
1.9 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, Header
from typing import List, Optional
from pydantic import BaseModel
import logging
from config import getConfig
from minio import Minio
import random
import tempfile
import traceback
router = APIRouter(
prefix="/images",
tags=["Images"],
responses={404: {"description": "Not found"}}
)
@router.get("/background/random")
async def background(accept: str = Header(None)):
"""
Will obtain a random image from the configured S3 bucket.
"""
endpoint = getConfig()["images.endpoint"]
access_key = getConfig()["images.access_key"]
secret_key = getConfig()["images.secret_key"]
bucket = getConfig()["images.bucket"]
secure = getConfig()["images.secure"]
try:
client = Minio(
endpoint,
access_key=access_key,
secret_key=secret_key,
secure=secure
)
objects = client.list_objects(bucket)
object_names = [obj.object_name for obj in objects]
if not object_names:
raise HTTPException(status_code=500, detail="No data in bucket!")
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}"
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}"})
return object_url
except Exception as err:
traceback.print_exc()
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