frontend_server.py
1.9 KB
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
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)