-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServe.py
More file actions
28 lines (24 loc) · 1.29 KB
/
Serve.py
File metadata and controls
28 lines (24 loc) · 1.29 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
# Serve React App
# This route serves 'index.html' for the root path and any other path not caught by an API route.
# It also serves static files like JS, CSS, images from the React build directory.
from flask import Flask, send_from_directory
import os
app = Flask(__name__)
REACT_BUILD_DIR = "ui/dist"
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve_react_app(path):
if path != "" and os.path.exists(os.path.join(REACT_BUILD_DIR, path)):
# If the path points to an existing file in the React build directory (e.g., static assets)
print(f"{REACT_BUILD_DIR}/{path}")
return send_from_directory(REACT_BUILD_DIR, path)
elif os.path.exists(os.path.join(REACT_BUILD_DIR, 'index.html')):
# Otherwise, serve the 'index.html'. This is crucial for client-side routing in React.
return send_from_directory(REACT_BUILD_DIR, 'index.html')
else:
# If 'index.html' is not found, return an error.
return "React build not found. Have you run `npm run build` in your React app directory (e.g., 'frontend')?", 404
# It's good practice to put app.run() inside a conditional
# to ensure it only runs when the script is executed directly.
if __name__ == '__main__':
app.run(debug=True) # Added debug=True for development convenience