From 9614267d4853b75b34ad8e447fd55cfabb99d87a Mon Sep 17 00:00:00 2001 From: Till Tomczak Date: Fri, 23 May 2025 08:56:29 +0200 Subject: [PATCH] "Refactor backend configuration and setup for improved maintainability (feat)" --- backend/app.py | 16 ++------------ backend/config.py | 32 +++++++++++++--------------- backend/test-backend-setup.py | 39 +++++++++++++++++++++-------------- backend/wsgi.py | 39 +++++++++++++++++++++-------------- 4 files changed, 62 insertions(+), 64 deletions(-) diff --git a/backend/app.py b/backend/app.py index 49222dc3..28367eb0 100755 --- a/backend/app.py +++ b/backend/app.py @@ -1952,19 +1952,7 @@ else: with app.app_context(): init_db() - printers_config = json.loads(app.config.get('PRINTERS', '{}')) + printers_config = app.config.get('PRINTERS', {}) if printers_config: init_printers() - setup_frontend_v2() - - # Parse PRINTERS als JSON - printers_env = app.config.get('PRINTERS', '{}') - if isinstance(printers_env, str): - try: - app.config['PRINTERS'] = json.loads(printers_env) - except (json.JSONDecodeError, TypeError): - app.config['PRINTERS'] = {} - elif isinstance(printers_env, dict): - app.config['PRINTERS'] = printers_env - else: - app.config['PRINTERS'] = {} \ No newline at end of file + setup_frontend_v2() \ No newline at end of file diff --git a/backend/config.py b/backend/config.py index afac0fca..23e03f1c 100644 --- a/backend/config.py +++ b/backend/config.py @@ -125,6 +125,11 @@ class ProductionConfig(Config): if not os.path.exists('logs'): os.mkdir('logs') + # Prüfe ob Datei-Logging deaktiviert ist (für Tests) + if app.config.get('DISABLE_FILE_LOGGING', False): + app.logger.info('Datei-Logging deaktiviert (Test-Modus)') + return + # Windows-kompatibles Logging import platform if platform.system() == 'Windows': @@ -205,30 +210,21 @@ class ProductionConfig(Config): app.logger.warning('Security module not found, skipping security middleware') class TestingConfig(Config): - """Konfiguration für die Testumgebung.""" - - DEBUG = True + """Konfiguration für Tests""" TESTING = True - - # In-Memory-Datenbank für Tests - DATABASE = ':memory:' - - # Deaktiviere CSRF für Tests + DEBUG = True WTF_CSRF_ENABLED = False + DATABASE_PATH = ':memory:' # In-Memory-Datenbank für Tests - # Kürzere Session-Lebensdauer für Tests - PERMANENT_SESSION_LIFETIME = timedelta(minutes=5) - - # Kürzere Job-Check-Intervalle für Tests - JOB_CHECK_INTERVAL = 5 - - # Deaktiviere Sicherheit für Tests - SECURITY_ENABLED = False - RATE_LIMIT_ENABLED = False + # Deaktiviere Datei-Logging für Tests (Windows-Kompatibilität) + DISABLE_FILE_LOGGING = True @staticmethod def init_app(app): - Config.init_app(app) + """Initialisierung für Test-Umgebung""" + # Nur Console-Logging für Tests + import logging + app.logger.setLevel(logging.WARNING) # Reduziere Log-Level für Tests # Konfigurationsmapping config = { diff --git a/backend/test-backend-setup.py b/backend/test-backend-setup.py index de9606fb..7f44d1f6 100644 --- a/backend/test-backend-setup.py +++ b/backend/test-backend-setup.py @@ -199,28 +199,35 @@ def test_health_endpoint(): print("🏥 Teste Health-Check...") try: - os.environ['SECRET_KEY'] = 'test_secret_key' - os.environ['DATABASE_PATH'] = ':memory:' - + # Verwende Test-Konfiguration um Logging-Probleme zu vermeiden from app import create_app - app = create_app('testing') with app.test_client() as client: - response = client.get('/health') + # Teste sowohl /health als auch /monitoring/health + endpoints_to_test = ['/health', '/monitoring/health'] - if response.status_code == 200: - data = response.get_json() - if data and data.get('status') == 'healthy': - print(" ✅ Health-Check funktioniert") - print(f" ✅ Service: {data.get('service')}") - return True + for endpoint in endpoints_to_test: + response = client.get(endpoint) + + if response.status_code == 200: + data = response.get_json() + if data and (data.get('status') == 'healthy' or data.get('status') == 'ok'): + print(f" ✅ Health-Check funktioniert ({endpoint})") + return True + else: + print(f" ❌ Health-Check-Response ungültig ({endpoint}): {data}") + continue else: - print(f" ❌ Health-Check-Antwort fehlerhaft: {data}") - return False - else: - print(f" ❌ Health-Check fehlgeschlagen: {response.status_code}") - return False + print(f" ❌ Health-Check fehlgeschlagen ({endpoint}): {response.status_code}") + continue + + # Wenn alle Endpoints fehlschlagen, zeige verfügbare Routen + print(" 📋 Verfügbare Health-Routen:") + for rule in app.url_map.iter_rules(): + if 'health' in rule.rule.lower(): + print(f" - {rule.rule} [{', '.join(rule.methods)}]") + return False except Exception as e: print(f" ❌ Health-Check-Fehler: {e}") diff --git a/backend/wsgi.py b/backend/wsgi.py index 5650bdab..ca121120 100644 --- a/backend/wsgi.py +++ b/backend/wsgi.py @@ -1,37 +1,44 @@ +#!/usr/bin/env python3 """ -WSGI-Einstiegspunkt für die MYP Flask-Anwendung. -Verwendet für den Produktionsbetrieb mit WSGI-Servern wie Gunicorn. +WSGI-Konfiguration für MYP Backend +Lädt die Flask-Anwendung für Produktions-Deployment mit Gunicorn """ import os -from dotenv import load_dotenv +import sys +import json -# Lade Umgebungsvariablen -load_dotenv() +# Füge das Backend-Verzeichnis zum Python-Pfad hinzu +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from app import create_app +from app import create_app, init_db, init_printers, setup_frontend_v2 -# Erstelle Anwendungsinstanz für Produktionsbetrieb +# Bestimme die Umgebung flask_env = os.environ.get('FLASK_ENV', 'production') + +# Erstelle die Flask-Anwendung application = create_app(flask_env) # Initialisierung für WSGI-Server with application.app_context(): - from app import init_db, init_printers, setup_frontend_v2 - import json - # Datenbank initialisieren init_db() - # Drucker initialisieren, falls konfiguriert - printers_config = json.loads(application.config.get('PRINTERS', '{}')) + # Drucker initialisieren (falls konfiguriert) + printers_config = application.config.get('PRINTERS', {}) if printers_config: init_printers() - # Frontend v2 Setup + # Frontend V2 einrichten setup_frontend_v2() - - application.logger.info(f'MYP Backend gestartet in {flask_env} Modus') + +# Logging für WSGI-Start +if hasattr(application, 'logger'): + application.logger.info(f'MYP Backend WSGI application started in {flask_env} mode') + +# Export für Gunicorn +app = application if __name__ == "__main__": - application.run() \ No newline at end of file + # Für direkte Ausführung (Debug) + application.run(host='0.0.0.0', port=5000, debug=(flask_env == 'development')) \ No newline at end of file