Files
website/start-flask-server.py

119 lines
3.7 KiB
Python

#!/usr/bin/env python3
import os
import sys
import time
import subprocess
import webbrowser
import requests
import socket
import logging
from pathlib import Path
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
def is_port_in_use(port):
"""Check if a port is already in use"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('127.0.0.1', port)) == 0
def wait_for_server(url, max_attempts=5, delay=1):
"""Wait for the server to start responding"""
for i in range(max_attempts):
try:
response = requests.get(url, timeout=2)
if response.status_code == 200:
logger.info(f"Server is up and running at {url}")
return True
except requests.exceptions.RequestException:
logger.info(f"Waiting for server to start (attempt {i+1}/{max_attempts})...")
time.sleep(delay)
return False
def main():
# Get the current directory
current_dir = Path(__file__).parent.absolute()
website_dir = current_dir / 'website'
# Check if website directory exists
if not website_dir.exists():
logger.error(f"Website directory not found: {website_dir}")
return False
# Flask server details
host = "127.0.0.1"
port = 5000
url = f"http://{host}:{port}"
# Check if the port is already in use
if is_port_in_use(port):
logger.warning(f"Port {port} is already in use. There might be another server running.")
answer = input("Would you like to try to connect to the existing server? (y/n): ")
if answer.lower() == 'y':
webbrowser.open(url)
return True
else:
logger.info("Please stop the other server and try again.")
return False
# Path to the run.py script
run_script = website_dir / 'run.py'
# Check if run.py exists
if not run_script.exists():
logger.error(f"Run script not found: {run_script}")
return False
# Start the Flask server in a separate process
logger.info(f"Starting Flask server from {run_script}...")
try:
# Use Python executable from the current environment
python_exe = sys.executable
# Start the server as a separate process
server_process = subprocess.Popen(
[python_exe, str(run_script)],
cwd=str(website_dir),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1
)
# Wait for server to start
server_started = wait_for_server(url, max_attempts=10, delay=2)
if server_started:
logger.info("Opening web browser...")
webbrowser.open(url)
# Keep the server running and display its output
logger.info("Server is running. Press Ctrl+C to stop.")
try:
for line in server_process.stdout:
print(line.strip())
except KeyboardInterrupt:
logger.info("Stopping server...")
server_process.terminate()
return True
else:
logger.error("Failed to start the server or server not responding")
server_process.terminate()
return False
except Exception as e:
logger.error(f"Error starting Flask server: {e}")
return False
if __name__ == "__main__":
success = main()
if not success:
print("\nPress Enter to exit...")
input()
sys.exit(0 if success else 1)