diff --git a/backend/api/static_files.py b/backend/api/static_files.py index f9850066..f38426ba 100644 --- a/backend/api/static_files.py +++ b/backend/api/static_files.py @@ -1,18 +1,9 @@ -"""Single-page application middleware. - -Our application is organized as a single-page application (SPA). This middleware class -extends the functionality of the StaticFiles middleware and was inspired by: - -""" - -__authors__ = ["Kris Jordan"] -__copyright__ = "Copyright 2023" -__license__ = "MIT" - +from fastapi import Response +from starlette.responses import FileResponse +from starlette.staticfiles import StaticFiles +from starlette.types import Scope import os -from fastapi.staticfiles import StaticFiles - class StaticFileMiddleware(StaticFiles): def __init__(self, directory: os.PathLike, index: str = "index.html") -> None: @@ -35,3 +26,21 @@ def lookup_path(self, path: str) -> tuple[str, os.stat_result | None]: return (full_path, stat_result) else: return (full_path, stat_result) + + async def get_response(self, path: str, scope: Scope) -> Response: + """Override get_response to set cache-control headers for index.html.""" + + # Explicitly handle the root path ("/") + if path in ["", "/", "."]: + path = self.index # Treat the root as a request for index.html + + full_path, _ = self.lookup_path(path) + + # If serving index.html, set cache-control header to prevent caching + if full_path.endswith(self.index): + response = FileResponse(full_path) + response.headers["Cache-Control"] = "no-store" + return response + + # For other static files, let the default caching behavior handle it + return await super().get_response(path, scope) diff --git a/backend/main.py b/backend/main.py index 2b2beace..d67aedfe 100644 --- a/backend/main.py +++ b/backend/main.py @@ -110,12 +110,12 @@ # Add application-wide exception handling middleware for commonly encountered API Exceptions @app.exception_handler(UserPermissionException) -def permission_exception_handler(request: Request, e: UserPermissionException): +def user_permission_exception_handler(request: Request, e: UserPermissionException): return JSONResponse(status_code=403, content={"message": str(e)}) @app.exception_handler(CoursePermissionException) -def permission_exception_handler(request: Request, e: UserPermissionException): +def course_permission_exception_handler(request: Request, e: UserPermissionException): return JSONResponse(status_code=403, content={"message": str(e)}) @@ -132,9 +132,7 @@ def reservation_exception_handler(request: Request, e: ReservationException): @app.exception_handler(CourseDataScrapingException) -def resource_not_found_exception_handler( - request: Request, e: CourseDataScrapingException -): +def course_data_scraping_exception(request: Request, e: CourseDataScrapingException): return JSONResponse(status_code=500, content={"message": str(e)})