Refactor: Optimize static file caching for WebUI
- Renamed `NoCacheStaticFiles` to `SmartStaticFiles`. - Implemented long-term caching (1 year, immutable) for versioned assets in `/webui/assets/`. - Ensured `index.html` remains un-cached. - Set correct `Content-Type` for JS and CSS files.
This commit is contained in:
@@ -478,18 +478,25 @@ def create_app(args):
|
|||||||
logger.error(f"Error getting health status: {str(e)}")
|
logger.error(f"Error getting health status: {str(e)}")
|
||||||
raise HTTPException(status_code=500, detail=str(e))
|
raise HTTPException(status_code=500, detail=str(e))
|
||||||
|
|
||||||
# Custom StaticFiles class to prevent caching of HTML files
|
# Custom StaticFiles class for smart caching
|
||||||
class NoCacheStaticFiles(StaticFiles):
|
class SmartStaticFiles(StaticFiles): # Renamed from NoCacheStaticFiles
|
||||||
async def get_response(self, path: str, scope):
|
async def get_response(self, path: str, scope):
|
||||||
response = await super().get_response(path, scope)
|
response = await super().get_response(path, scope)
|
||||||
|
|
||||||
if path.endswith(".html"):
|
if path.endswith(".html"):
|
||||||
response.headers["Cache-Control"] = (
|
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
|
||||||
"no-cache, no-store, must-revalidate"
|
|
||||||
)
|
|
||||||
response.headers["Pragma"] = "no-cache"
|
response.headers["Pragma"] = "no-cache"
|
||||||
response.headers["Expires"] = "0"
|
response.headers["Expires"] = "0"
|
||||||
elif path.endswith(".js"):
|
elif "/assets/" in path: # Assets (JS, CSS, images, fonts) generated by Vite with hash in filename
|
||||||
|
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
|
||||||
|
# Add other rules here if needed for non-HTML, non-asset files
|
||||||
|
|
||||||
|
# Ensure correct Content-Type
|
||||||
|
if path.endswith(".js"):
|
||||||
response.headers["Content-Type"] = "application/javascript"
|
response.headers["Content-Type"] = "application/javascript"
|
||||||
|
elif path.endswith(".css"):
|
||||||
|
response.headers["Content-Type"] = "text/css"
|
||||||
|
|
||||||
return response
|
return response
|
||||||
|
|
||||||
# Webui mount webui/index.html
|
# Webui mount webui/index.html
|
||||||
@@ -497,7 +504,7 @@ def create_app(args):
|
|||||||
static_dir.mkdir(exist_ok=True)
|
static_dir.mkdir(exist_ok=True)
|
||||||
app.mount(
|
app.mount(
|
||||||
"/webui",
|
"/webui",
|
||||||
NoCacheStaticFiles(directory=static_dir, html=True, check_dir=True),
|
SmartStaticFiles(directory=static_dir, html=True, check_dir=True), # Use SmartStaticFiles
|
||||||
name="webui",
|
name="webui",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user