Spaces:
Sleeping
Sleeping
File size: 2,119 Bytes
2abe322 80541ef 2abe322 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | # 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)
)
@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
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)
@app.route("/_health")
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)
|