home.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. #!/usr/bin/env python
  2. """
  3. @Contact : liuyuqi.gov@msn.cn
  4. @Time : 2024/03/22 09:27:16
  5. @License : Copyright © 2017-2022 liuyuqi. All Rights Reserved.
  6. @Desc :
  7. """
  8. from fastapi import APIRouter, FastAPI, Request, HTTPException, status
  9. from fastapi.responses import (
  10. StreamingResponse,
  11. JSONResponse,
  12. HTMLResponse,
  13. FileResponse,
  14. RedirectResponse,
  15. Response,
  16. )
  17. from pathlib import Path
  18. router = APIRouter()
  19. @router.get("/")
  20. async def index():
  21. return {"code": 200, "message": "this is backend api"}
  22. @app.get("/{full_path:path}", include_in_schema=False)
  23. def spa(full_path: str):
  24. dist_dir = Path(__file__).parent / "dist"
  25. # TODO: hacky way to only serve index.html on root urls
  26. files = [entry.name for entry in dist_dir.iterdir() if entry.is_file()]
  27. if full_path in files:
  28. return FileResponse(dist_dir / full_path)
  29. if "." in full_path:
  30. raise HTTPException(status_code=404, detail="Asset not found")
  31. return HTMLResponse((dist_dir / "index.html").read_bytes())