Kexin-251202 commited on
Commit
4916337
·
verified ·
1 Parent(s): 2eba0cc

update main.py STATIC FILES (SPA SUPPORT)

Browse files
Files changed (1) hide show
  1. main.py +14 -15
main.py CHANGED
@@ -1188,24 +1188,23 @@ async def health_check():
1188
 
1189
  # ================ STATIC FILES (SPA SUPPORT) ================
1190
 
1191
- # Resolve static dir from this file so it works regardless of cwd
1192
- _STATIC_DIR = Path(__file__).resolve().parent / "static"
1193
- _ASSETS_DIR = _STATIC_DIR / "assets"
1194
 
1195
- # 1. Mount the assets folder (JS/CSS) first so /assets/* is never caught by catch-all
1196
- if _ASSETS_DIR.is_dir():
1197
- app.mount("/assets", StaticFiles(directory=str(_ASSETS_DIR)), name="assets")
1198
 
1199
- # 2. Catch-all for SPA: serve index.html for app routes, never for /assets (would break JS MIME type)
1200
  @app.get("/{full_path:path}")
1201
  async def serve_react_app(full_path: str, request: Request):
1202
  if full_path.startswith("api") or full_path.startswith("ws"):
1203
  raise HTTPException(status_code=404, detail="Not Found")
1204
- # Don't serve HTML for asset paths; let them 404 so we don't break module script loading
1205
- if full_path.startswith("assets") or full_path.startswith("assets/"):
1206
- raise HTTPException(status_code=404, detail="Not Found")
1207
-
1208
- index_path = _STATIC_DIR / "index.html"
1209
- if index_path.is_file():
1210
- return FileResponse(str(index_path))
1211
- return {"message": "React app not found. Please run 'npm run build' and copy dist to static."}
 
 
 
1188
 
1189
  # ================ STATIC FILES (SPA SUPPORT) ================
1190
 
1191
+ FRONTEND_DIR = "dist" if os.path.exists("dist/index.html") else "static"
 
 
1192
 
1193
+ assets_path = os.path.join(FRONTEND_DIR, "assets")
1194
+ if os.path.exists(assets_path):
1195
+ app.mount("/assets", StaticFiles(directory=assets_path), name="assets")
1196
 
 
1197
  @app.get("/{full_path:path}")
1198
  async def serve_react_app(full_path: str, request: Request):
1199
  if full_path.startswith("api") or full_path.startswith("ws"):
1200
  raise HTTPException(status_code=404, detail="Not Found")
1201
+
1202
+ file_path = os.path.join(FRONTEND_DIR, full_path)
1203
+ if os.path.isfile(file_path):
1204
+ return FileResponse(file_path)
1205
+
1206
+ index_path = os.path.join(FRONTEND_DIR, "index.html")
1207
+ if os.path.exists(index_path):
1208
+ return FileResponse(index_path)
1209
+ else:
1210
+ return {"message": "React app not found. Please run npm run build."}