From c5539b442c010a2e2f494e5b86c059d434c131ca Mon Sep 17 00:00:00 2001 From: psychedelicious <4822129+psychedelicious@users.noreply.github.com> Date: Sun, 9 Jul 2023 22:42:05 +1000 Subject: [PATCH] feat(api): set max-age for images Image files are immutable and we expect deletion to result in no further requests for a given image, so we can set the max-age to something thicc. Resolves #3426 --- invokeai/app/api/routers/images.py | 31 +++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/invokeai/app/api/routers/images.py b/invokeai/app/api/routers/images.py index a8c84b81b9..f727bd4ee2 100644 --- a/invokeai/app/api/routers/images.py +++ b/invokeai/app/api/routers/images.py @@ -1,25 +1,26 @@ import io from typing import Optional -from fastapi import Body, HTTPException, Path, Query, Request, Response, UploadFile -from fastapi.routing import APIRouter + +from fastapi import (Body, HTTPException, Path, Query, Request, Response, + UploadFile) from fastapi.responses import FileResponse +from fastapi.routing import APIRouter from PIL import Image -from invokeai.app.models.image import ( - ImageCategory, - ResourceOrigin, -) + +from invokeai.app.models.image import ImageCategory, ResourceOrigin from invokeai.app.services.image_record_storage import OffsetPaginatedResults -from invokeai.app.services.models.image_record import ( - ImageDTO, - ImageRecordChanges, - ImageUrlsDTO, -) from invokeai.app.services.item_storage import PaginatedResults +from invokeai.app.services.models.image_record import (ImageDTO, + ImageRecordChanges, + ImageUrlsDTO) from ..dependencies import ApiDependencies images_router = APIRouter(prefix="/v1/images", tags=["images"]) +# images are immutable; set a high max-age +IMAGE_MAX_AGE = 31536000 + @images_router.post( "/", @@ -141,12 +142,14 @@ async def get_image_full( if not ApiDependencies.invoker.services.images.validate_path(path): raise HTTPException(status_code=404) - return FileResponse( + response = FileResponse( path, media_type="image/png", filename=image_name, content_disposition_type="inline", ) + response.headers["Cache-Control"] = f"max-age={IMAGE_MAX_AGE}" + return response except Exception as e: raise HTTPException(status_code=404) @@ -175,9 +178,11 @@ async def get_image_thumbnail( if not ApiDependencies.invoker.services.images.validate_path(path): raise HTTPException(status_code=404) - return FileResponse( + response = FileResponse( path, media_type="image/webp", content_disposition_type="inline" ) + response.headers["Cache-Control"] = f"max-age={IMAGE_MAX_AGE}" + return response except Exception as e: raise HTTPException(status_code=404)