Repository navigation
Expand file tree
/
Copy pathrun_dev.py
More file actions
198 lines (164 loc) · 6.09 KB
/
Copy pathrun_dev.py
File metadata and controls
198 lines (164 loc) · 6.09 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#!/usr/bin/env python3
"""
Unified development server launcher for Flask + React application.
This script starts both the Flask backend and React frontend development servers.
"""
import os
import sys
import subprocess
import signal
import time
from pathlib import Path
def check_dependencies():
"""Check if required dependencies are available."""
# Check if npm is available
try:
subprocess.run(['npm', '--version'], capture_output=True, check=True)
except (subprocess.CalledProcessError, FileNotFoundError):
print("❌ npm is not installed or not in PATH")
print("Please install Node.js and npm first")
sys.exit(1)
# Check if Python dependencies are installed
try:
import flask
import flask_cors
import dotenv
import pandas
except ImportError as e:
print(f"❌ Missing Python dependency: {e}")
print("Please run: pip install -r requirements.txt")
sys.exit(1)
print("✅ All dependencies are available")
def install_npm_dependencies():
"""Install npm dependencies if node_modules doesn't exist."""
app_dir = Path("app")
node_modules = app_dir / "node_modules"
if not node_modules.exists():
print("📦 Installing npm dependencies...")
try:
subprocess.run(['npm', 'install'], cwd=app_dir, check=True)
print("✅ npm dependencies installed")
except subprocess.CalledProcessError:
print("❌ Failed to install npm dependencies")
sys.exit(1)
else:
print("✅ npm dependencies already installed")
def build_react_app():
"""Build the React application for production."""
app_dir = Path("app")
print("🔨 Building React application...")
try:
subprocess.run(['npm', 'run', 'build'], cwd=app_dir, check=True)
print("✅ React application built successfully")
except subprocess.CalledProcessError:
print("❌ Failed to build React application")
sys.exit(1)
def start_flask_server():
"""Start the Flask server."""
print("🚀 Starting Flask server...")
# Set environment variables
env = os.environ.copy()
env['FLASK_ENV'] = 'development'
env['FLASK_DEBUG'] = '1'
try:
flask_process = subprocess.Popen(
[sys.executable, 'app.py'],
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
bufsize=1
)
return flask_process
except Exception as e:
print(f"❌ Failed to start Flask server: {e}")
sys.exit(1)
def start_react_dev_server():
"""Start the React development server."""
app_dir = Path("app")
print("🚀 Starting React development server...")
try:
react_process = subprocess.Popen(
['npm', 'run', 'dev'],
cwd=app_dir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
bufsize=1
)
return react_process
except Exception as e:
print(f"❌ Failed to start React development server: {e}")
sys.exit(1)
def monitor_processes(flask_process, react_process):
"""Monitor both processes and handle output."""
print("\n" + "="*60)
print("🎉 Both servers are starting up!")
print("📱 React dev server: http://localhost:5173")
print("🐍 Flask API server: http://localhost:5001")
print("="*60)
print("\n💡 Press Ctrl+C to stop both servers\n")
try:
while True:
# Check if processes are still running
flask_poll = flask_process.poll()
react_poll = react_process.poll()
if flask_poll is not None:
print(f"❌ Flask server exited with code {flask_poll}")
break
if react_poll is not None:
print(f"❌ React server exited with code {react_poll}")
break
time.sleep(1)
except KeyboardInterrupt:
print("\n🛑 Shutting down servers...")
# Terminate processes gracefully
flask_process.terminate()
react_process.terminate()
# Wait a bit for graceful shutdown
time.sleep(2)
# Force kill if still running
if flask_process.poll() is None:
flask_process.kill()
if react_process.poll() is None:
react_process.kill()
print("✅ Servers stopped")
def main():
"""Main function to orchestrate the development environment."""
print("🚀 Starting Transit Map Development Environment")
print("=" * 50)
# Check dependencies
check_dependencies()
# Install npm dependencies if needed
install_npm_dependencies()
# Ask user which mode they prefer
print("\nChoose development mode:")
print("1. Development mode (Flask + React dev server)")
print("2. Production mode (Flask serves built React app)")
choice = input("Enter choice (1 or 2, default: 1): ").strip()
if choice == "2":
# Production mode - build React and run only Flask
build_react_app()
flask_process = start_flask_server()
print("\n" + "="*60)
print("🎉 Production server is running!")
print("🌐 Application: http://localhost:5001")
print("="*60)
print("\n💡 Press Ctrl+C to stop the server\n")
try:
flask_process.wait()
except KeyboardInterrupt:
print("\n🛑 Shutting down server...")
flask_process.terminate()
time.sleep(2)
if flask_process.poll() is None:
flask_process.kill()
print("✅ Server stopped")
else:
# Development mode - run both servers
flask_process = start_flask_server()
time.sleep(2) # Give Flask a moment to start
react_process = start_react_dev_server()
monitor_processes(flask_process, react_process)
if __name__ == "__main__":
main()