Add Flask server startup scripts: introduce start_server.bat for Windows and start-flask-server.py for enhanced server management. Update run.py to include logging and threaded request handling. Add test_server.py for server accessibility testing.
This commit is contained in:
119
start-flask-server.py
Normal file
119
start-flask-server.py
Normal file
@@ -0,0 +1,119 @@
|
||||
#!/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)
|
||||
5
start_server.bat
Normal file
5
start_server.bat
Normal file
@@ -0,0 +1,5 @@
|
||||
@echo off
|
||||
cd website
|
||||
echo Starting Flask server on http://127.0.0.1:5000
|
||||
python run.py
|
||||
pause
|
||||
25
test_server.py
Normal file
25
test_server.py
Normal file
@@ -0,0 +1,25 @@
|
||||
import requests
|
||||
import time
|
||||
|
||||
def test_flask_server():
|
||||
"""Test if the Flask server is accessible at http://127.0.0.1:5000"""
|
||||
url = "http://127.0.0.1:5000"
|
||||
|
||||
print(f"Testing connection to Flask server at {url}")
|
||||
|
||||
for i in range(3):
|
||||
try:
|
||||
response = requests.get(url, timeout=5)
|
||||
print(f"SUCCESS! Status code: {response.status_code}")
|
||||
return True
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"Attempt {i+1} failed: {e}")
|
||||
if i < 2:
|
||||
print("Waiting 2 seconds and trying again...")
|
||||
time.sleep(2)
|
||||
|
||||
print("Failed to connect to the Flask server after 3 attempts")
|
||||
return False
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_flask_server()
|
||||
@@ -1,10 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import sys
|
||||
import logging
|
||||
from app import create_app
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
app = create_app()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Run the app directly - no need to call init_database as it doesn't exist
|
||||
app.run(host="0.0.0.0", debug=True)
|
||||
logger.info("Starting Flask server on http://127.0.0.1:5000")
|
||||
try:
|
||||
# Use threaded=True for better request handling
|
||||
app.run(host="127.0.0.1", port=5000, debug=True, use_reloader=False, threaded=True)
|
||||
except Exception as e:
|
||||
logger.error(f"Error starting Flask server: {e}")
|
||||
sys.exit(1)
|
||||
Reference in New Issue
Block a user