Projektarbeit-MYP/backend/start_kiosk_fixed.py

179 lines
5.3 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
KIOSK-STARTUP SCRIPT (WINDOWS-OPTIMIERT)
=========================================
Startet die Flask-App mit Waitress für stabilen Kiosk-Betrieb.
Behebt "unreachable" und Performance-Probleme.
"""
import os
import sys
import time
import signal
import socket
import subprocess
import threading
from pathlib import Path
# Umgebungsvariablen für optimierte Konfiguration setzen
os.environ["FORCE_OPTIMIZED_MODE"] = "true"
os.environ["USE_OPTIMIZED_CONFIG"] = "true"
os.environ["FLASK_ENV"] = "production"
os.environ["PYTHONUNBUFFERED"] = "1"
def kill_hanging_processes():
"""Beendet hängende Flask-Prozesse auf Port 5000"""
print("🔄 Beende hängende Prozesse...")
try:
result = subprocess.run(
["netstat", "-ano"],
capture_output=True,
text=True,
shell=True
)
hanging_pids = set()
for line in result.stdout.split('\n'):
if ":5000" in line and ("WARTEND" in line or "ESTABLISHED" in line):
parts = line.split()
if len(parts) >= 5:
pid = parts[-1]
if pid.isdigit() and int(pid) != 0:
hanging_pids.add(int(pid))
for pid in hanging_pids:
try:
subprocess.run(["taskkill", "/F", "/PID", str(pid)],
capture_output=True, shell=True)
print(f"💀 Prozess {pid} beendet")
except:
pass
if hanging_pids:
print(f"{len(hanging_pids)} hängende Prozesse beendet")
time.sleep(2)
else:
print("✅ Keine hängenden Prozesse gefunden")
except Exception as e:
print(f"⚠️ Prozess-Cleanup fehlgeschlagen: {e}")
def test_app_response(host="127.0.0.1", port=5000, timeout=10):
"""Testet ob die App antwortet"""
print(f"🔍 Teste App-Antwort auf {host}:{port}...")
for i in range(timeout):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((host, port))
sock.close()
if result == 0:
print(f"✅ App erreichbar nach {i+1} Sekunden")
return True
except:
pass
time.sleep(1)
print(f"⏳ Warte... ({i+1}/{timeout})")
print("❌ App nicht erreichbar!")
return False
def start_app_with_waitress():
"""Startet die App mit Waitress"""
print("🚀 Starte App mit Waitress WSGI-Server...")
# Cleanup zuerst
kill_hanging_processes()
# Importiere App-Module
try:
print("📦 Importiere Flask-App...")
sys.path.insert(0, str(Path(__file__).parent))
# App importieren und Optimierungen aktivieren
from app import app
# Stelle sicher, dass optimierte Konfiguration aktiv ist
app.config.update({
"DEBUG": False,
"TESTING": False,
"TEMPLATES_AUTO_RELOAD": False,
"SEND_FILE_MAX_AGE_DEFAULT": 31536000, # 1 Jahr Cache
})
print("✅ Flask-App erfolgreich importiert")
except Exception as e:
print(f"❌ Fehler beim App-Import: {e}")
return False
# Starte Waitress in separatem Thread
print("🖥️ Starte Waitress-Server...")
def run_waitress():
try:
from waitress import serve
serve(
app,
host="127.0.0.1", # IPv4 only
port=5000,
threads=6, # Multi-threading für bessere Performance
connection_limit=200,
cleanup_interval=30,
channel_timeout=120,
log_untrusted_proxy_headers=False,
clear_untrusted_proxy_headers=True,
max_request_header_size=8192,
max_request_body_size=104857600, # 100MB
expose_tracebacks=False
)
except Exception as e:
print(f"❌ Waitress-Fehler: {e}")
# Server in Thread starten
server_thread = threading.Thread(target=run_waitress, daemon=True)
server_thread.start()
# Kurz warten und testen
time.sleep(3)
if test_app_response():
print("🎉 APP ERFOLGREICH GESTARTET!")
print("📋 Kiosk-URL: http://127.0.0.1:5000")
print("💡 IPv6-Probleme behoben durch IPv4-only")
print("🚀 Stable WSGI-Server statt Flask-Dev-Server")
return True
else:
print("❌ App startet nicht korrekt!")
return False
def main():
"""Hauptfunktion"""
print("🔧 KIOSK-FIX GESTARTET")
print("=" * 50)
if len(sys.argv) > 1 and sys.argv[1] == "--kill":
kill_hanging_processes()
return
if start_app_with_waitress():
try:
print("\n⌨️ Drücke CTRL+C zum Beenden...")
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\n🛑 CTRL+C erkannt - beende App...")
print("✅ App gestoppt")
else:
print("❌ App-Start fehlgeschlagen!")
sys.exit(1)
if __name__ == "__main__":
main()