frontend_server.py 1.9 KB
import os
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from middleware import IPFilterMiddleware

app = FastAPI()

# Add IP Filter Middleware
app.add_middleware(IPFilterMiddleware)

# Frontend Dist Path
DIST_DIR = os.path.join(os.path.dirname(__file__), "z-image-generator", "dist")

# Ensure dist exists
if not os.path.exists(DIST_DIR):
    os.makedirs(DIST_DIR, exist_ok=True)
    # Create a dummy index.html if not exists for testing
    with open(os.path.join(DIST_DIR, "index.html"), "w") as f:
        f.write("<h1>Frontend Build Not Found</h1>")

# Serve Static Files
# We mount root to serve static files, BUT we need SPA fallback.
# Solution: Mount specific assets folder, and use a catch-all for index.html

# 1. Mount /assets if it exists in dist
assets_path = os.path.join(DIST_DIR, "assets")
if os.path.exists(assets_path):
    app.mount("/assets", StaticFiles(directory=assets_path), name="assets")

# 2. Serve other static files (like favicon, etc) if needed?
# For simplicity, we just use a catch-all route to serve index.html or the file if it exists
@app.get("/{full_path:path}")
async def serve_spa(full_path: str):
    # Check if file exists in dist
    file_path = os.path.join(DIST_DIR, full_path)
    if os.path.exists(file_path) and os.path.isfile(file_path):
        return FileResponse(file_path)
    
    # Fallback to index.html for SPA
    # Disable cache for index.html to ensure updates are seen immediately
    response = FileResponse(os.path.join(DIST_DIR, "index.html"))
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "0"
    return response

if __name__ == "__main__":
    import uvicorn
    # Read port from env or default
    port = int(os.getenv("LOCAL_FRONTEND_PORT", "7001"))
    uvicorn.run(app, host="0.0.0.0", port=port)