Spaces:
Sleeping
Sleeping
| # app.py | |
| import os | |
| from pathlib import Path | |
| from flask import Flask, send_from_directory, render_template_string, abort | |
| # Configure where built frontend lives | |
| DIST_DIR = Path(__file__).parent.joinpath("dist") | |
| app = Flask( | |
| __name__, | |
| static_folder=str(DIST_DIR), # serve static files from dist/ | |
| static_url_path="" # serve them from root (so /assets/... works) | |
| ) | |
| def serve_spa(path: str): | |
| """ | |
| Serve files from dist/ when they exist. | |
| If a file doesn't exist, serve index.html (SPA fallback). | |
| If dist/index.html is missing, show a helpful message. | |
| """ | |
| # If dist doesn't exist or index.html missing, show message. | |
| index_file = DIST_DIR / "index.html" | |
| if not index_file.exists(): | |
| msg = """ | |
| <h2>Static frontend not found (dist/index.html)</h2> | |
| <p>The Space is running but the built frontend (dist/) is missing.</p> | |
| <p>Possible fixes:</p> | |
| <ol> | |
| <li>Ensure your GitHub Actions builds the Vite app and copies <code>dist/</code> into the Space repo root.</li> | |
| <li>Or manually build locally and copy the <code>dist/</code> contents into this repo.</li> | |
| </ol> | |
| <p>Once <code>dist/index.html</code> is present, the app will be served automatically.</p> | |
| """ | |
| return render_template_string(msg), 200 | |
| # If path points to an existing file in dist => serve it | |
| target = DIST_DIR.joinpath(path) | |
| if path != "" and target.exists() and target.is_file(): | |
| # send direct file, preserves mime types | |
| return send_from_directory(str(DIST_DIR), path) | |
| # Otherwise return index.html (SPA fallback) | |
| return send_from_directory(str(DIST_DIR), "index.html") | |
| # Health endpoint (optional) | |
| def health(): | |
| return {"status": "ok"}, 200 | |
| if __name__ == "__main__": | |
| # When launched by HF Spaces, this script will be executed directly. | |
| # Use environment PORT if provided, else default 7860. | |
| port = int(os.environ.get("PORT", 7860)) | |
| app.run(host="0.0.0.0", port=port) | |