Serve frontend from the root
This commit is contained in:
@ -7,11 +7,10 @@ import logging
|
||||
import pathlib
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, Request, status
|
||||
from fastapi import FastAPI, HTTPException, Request, status
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
@ -42,17 +41,6 @@ def valid_frontend_directory(frontend_dir: pathlib.Path) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def setup_frontend(app: FastAPI, settings: AdminServerSettings) -> None:
|
||||
"""Setup frontend."""
|
||||
if not settings.frontend_dir:
|
||||
return
|
||||
if not valid_frontend_directory(settings.frontend_dir):
|
||||
LOG.error("Error: Not a valid frontend directory: %s", settings.frontend_dir)
|
||||
return
|
||||
frontend = StaticFiles(directory=settings.frontend_dir)
|
||||
app.mount("/admin", frontend, name="frontend")
|
||||
|
||||
|
||||
def create_admin_app(
|
||||
settings: AdminServerSettings,
|
||||
create_db: bool = False,
|
||||
@ -128,6 +116,25 @@ def create_admin_app(
|
||||
dependencies = BaseDependencies(settings, get_db_session, get_async_session)
|
||||
|
||||
app.include_router(api.create_api_router(dependencies))
|
||||
setup_frontend(app, settings)
|
||||
|
||||
@app.get("/")
|
||||
def serve_frontend(request: Request) -> FileResponse:
|
||||
"""Serve the frontend SPA index."""
|
||||
LOG.info("Got this request: %r", request.url)
|
||||
if not settings.frontend_dir:
|
||||
raise HTTPException(status_code=404, detail="Not found.")
|
||||
return FileResponse(settings.frontend_dir / "index.html")
|
||||
|
||||
@app.get("/{frontend_path:path}")
|
||||
def serve_frontend_path(frontend_path: str) -> FileResponse:
|
||||
"""Serve the frontend SPA.."""
|
||||
LOG.info("Got request for %s", frontend_path)
|
||||
if not settings.frontend_dir:
|
||||
raise HTTPException(status_code=404, detail="Not found.")
|
||||
static_file = settings.frontend_dir / frontend_path
|
||||
if static_file.exists() and static_file.is_file():
|
||||
return FileResponse(static_file)
|
||||
return FileResponse(settings.frontend_dir / "index.html")
|
||||
|
||||
|
||||
return app
|
||||
|
||||
Reference in New Issue
Block a user