"Refactor backend configuration and setup for improved maintainability (feat)"

This commit is contained in:
Till Tomczak 2025-05-23 08:56:29 +02:00
parent a11721f677
commit 9614267d48
4 changed files with 62 additions and 64 deletions

View File

@ -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'] = {}

View File

@ -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 = {

View File

@ -199,27 +199,34 @@ 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']
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':
print(" ✅ Health-Check funktioniert")
print(f" ✅ Service: {data.get('service')}")
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-Antwort fehlerhaft: {data}")
return False
print(f" ❌ Health-Check-Response ungültig ({endpoint}): {data}")
continue
else:
print(f" ❌ Health-Check fehlgeschlagen: {response.status_code}")
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:

View File

@ -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()
# Für direkte Ausführung (Debug)
application.run(host='0.0.0.0', port=5000, debug=(flask_env == 'development'))