"feat: Enhanced backend installation script in install.ps1 and test-backend-setup.py"

This commit is contained in:
Till Tomczak 2025-05-23 08:58:42 +02:00
parent 9614267d48
commit 9fe529247b
2 changed files with 273 additions and 27 deletions

241
backend/install.ps1 Normal file
View File

@ -0,0 +1,241 @@
# MYP Backend - Windows PowerShell Installations-Skript
# Installiert das Backend für Produktionsbetrieb oder Entwicklung
param(
[switch]$Production,
[switch]$Development,
[switch]$Clean,
[switch]$Logs,
[switch]$Help
)
# Farben für PowerShell
$Red = "Red"
$Green = "Green"
$Yellow = "Yellow"
$Blue = "Cyan"
function Write-Log {
param([string]$Message, [string]$Color = "White")
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host "[$timestamp] $Message" -ForegroundColor $Color
}
function Write-Success {
param([string]$Message)
Write-Log "SUCCESS: $Message" -Color $Green
}
function Write-Warning {
param([string]$Message)
Write-Log "WARNING: $Message" -Color $Yellow
}
function Write-Error {
param([string]$Message)
Write-Log "FEHLER: $Message" -Color $Red
}
# Banner
Write-Host "========================================" -ForegroundColor $Blue
Write-Host "🏭 MYP Backend - Windows Installation" -ForegroundColor $Blue
Write-Host "========================================" -ForegroundColor $Blue
if ($Help) {
Write-Host @"
Verwendung: .\install.ps1 [OPTIONEN]
OPTIONEN:
-Production Produktions-Installation
-Development Entwicklungs-Installation
-Clean Bereinige vorherige Installation
-Logs Zeige detaillierte Logs
-Help Zeige diese Hilfe
BEISPIELE:
.\install.ps1 -Production
.\install.ps1 -Development -Logs
.\install.ps1 -Clean
"@
exit 0
}
# Bestimme Installationsmodus
$InstallMode = "development"
if ($Production) {
$InstallMode = "production"
Write-Log "🏭 Produktions-Installation gestartet" -Color $Blue
} elseif ($Development) {
$InstallMode = "development"
Write-Log "🔧 Entwicklungs-Installation gestartet" -Color $Blue
} else {
Write-Log "🔧 Standard-Installation (Entwicklung)" -Color $Blue
}
# Arbeitsverzeichnis prüfen
$CurrentDir = Get-Location
Write-Log "Arbeitsverzeichnis: $CurrentDir"
if (-not (Test-Path "app.py")) {
Write-Error "app.py nicht gefunden! Bitte im Backend-Verzeichnis ausführen."
exit 1
}
# Python-Version prüfen
Write-Log "🐍 Prüfe Python-Installation..." -Color $Blue
try {
$PythonVersion = python --version 2>&1
Write-Log "Python-Version: $PythonVersion"
# Prüfe Mindestversion (3.8+)
$VersionMatch = $PythonVersion -match "Python (\d+)\.(\d+)"
if ($VersionMatch) {
$Major = [int]$Matches[1]
$Minor = [int]$Matches[2]
if ($Major -lt 3 -or ($Major -eq 3 -and $Minor -lt 8)) {
Write-Error "Python 3.8+ erforderlich, gefunden: $PythonVersion"
exit 1
}
}
Write-Success "Python-Version ist kompatibel"
} catch {
Write-Error "Python nicht gefunden! Bitte Python 3.8+ installieren."
exit 1
}
# Bereinigung (falls gewünscht)
if ($Clean) {
Write-Log "🧹 Bereinige vorherige Installation..." -Color $Yellow
if (Test-Path "instance") {
Remove-Item -Recurse -Force "instance"
Write-Log "Datenbank-Verzeichnis entfernt"
}
if (Test-Path "logs") {
Remove-Item -Recurse -Force "logs"
Write-Log "Log-Verzeichnis entfernt"
}
Write-Success "Bereinigung abgeschlossen"
}
# Erstelle erforderliche Verzeichnisse
Write-Log "📁 Erstelle Verzeichnisse..." -Color $Blue
$Directories = @("instance", "logs", "uploads")
foreach ($Dir in $Directories) {
if (-not (Test-Path $Dir)) {
New-Item -ItemType Directory -Path $Dir | Out-Null
Write-Log "Verzeichnis erstellt: $Dir"
} else {
Write-Log "Verzeichnis existiert bereits: $Dir"
}
}
# Installiere Python-Dependencies
Write-Log "📦 Installiere Python-Pakete..." -Color $Blue
if (Test-Path "requirements.txt") {
try {
if ($Logs) {
pip install -r requirements.txt
} else {
pip install -r requirements.txt --quiet
}
Write-Success "Python-Pakete installiert"
} catch {
Write-Error "Fehler beim Installieren der Python-Pakete: $_"
exit 1
}
} else {
Write-Warning "requirements.txt nicht gefunden"
}
# Umgebungskonfiguration
Write-Log "⚙️ Konfiguriere Umgebung..." -Color $Blue
if (Test-Path "env.backend") {
Write-Log "Umgebungskonfiguration gefunden: env.backend"
# Lade Umgebungsvariablen für Tests
$EnvContent = Get-Content "env.backend"
foreach ($Line in $EnvContent) {
if ($Line -match "^([^#][^=]+)=(.*)$") {
$Key = $Matches[1].Trim()
$Value = $Matches[2].Trim()
[Environment]::SetEnvironmentVariable($Key, $Value, "Process")
}
}
Write-Success "Umgebungsvariablen geladen"
} else {
Write-Warning "env.backend nicht gefunden"
}
# Datenbank initialisieren
Write-Log "🗄️ Initialisiere Datenbank..." -Color $Blue
try {
$env:FLASK_APP = "app.py"
$env:FLASK_ENV = $InstallMode
$PythonCode = "from app import create_app, init_db; app = create_app('$InstallMode'); app.app_context().push(); init_db(); print('Datenbank initialisiert')"
python -c $PythonCode
Write-Success "Datenbank erfolgreich initialisiert"
} catch {
Write-Error "Fehler bei der Datenbank-Initialisierung: $_"
exit 1
}
# Konfigurationstest
Write-Log "🧪 Teste Konfiguration..." -Color $Blue
try {
python test-backend-setup.py | Out-Null
$TestResult = $LASTEXITCODE
if ($TestResult -eq 0) {
Write-Success "Alle Konfigurationstests bestanden"
} else {
Write-Warning "Einige Konfigurationstests fehlgeschlagen (Code: $TestResult)"
if ($Logs) {
Write-Log "Führe detaillierte Tests aus..."
python test-backend-setup.py
}
}
} catch {
Write-Warning "Konfigurationstest konnte nicht ausgeführt werden: $_"
}
# Installation abgeschlossen
Write-Host ""
Write-Host "========================================" -ForegroundColor $Green
Write-Host "✅ MYP Backend Installation abgeschlossen!" -ForegroundColor $Green
Write-Host "========================================" -ForegroundColor $Green
Write-Host ""
Write-Host "📋 Nächste Schritte:" -ForegroundColor $Blue
Write-Host "1. Backend starten:" -ForegroundColor $White
Write-Host " .\start-backend-server.ps1" -ForegroundColor $Yellow
Write-Host ""
Write-Host "2. Health-Check testen:" -ForegroundColor $White
Write-Host " curl http://localhost:5000/monitoring/health/simple" -ForegroundColor $Yellow
Write-Host ""
Write-Host "3. Logs überwachen:" -ForegroundColor $White
Write-Host " Get-Content logs\myp.log -Wait" -ForegroundColor $Yellow
Write-Host ""
if ($InstallMode -eq "production") {
Write-Host "🏭 Produktions-Hinweise:" -ForegroundColor $Blue
Write-Host "- Verwende einen Reverse Proxy (nginx/Apache)" -ForegroundColor $White
Write-Host "- Konfiguriere SSL/TLS-Zertifikate" -ForegroundColor $White
Write-Host "- Überwache Logs und Metriken" -ForegroundColor $White
Write-Host "- Führe regelmäßige Backups durch" -ForegroundColor $White
}
Write-Host ""
Write-Success "Installation erfolgreich abgeschlossen!"

View File

@ -29,29 +29,31 @@ def test_dependencies():
"""Teste erforderliche Python-Pakete"""
print("📦 Teste Python-Dependencies...")
required_packages = [
'flask',
'flask_cors',
'werkzeug',
'pyjwt',
'python_dotenv',
'gunicorn'
]
required_packages = {
'flask': 'flask',
'flask_cors': 'flask_cors',
'werkzeug': 'werkzeug',
'jwt': 'PyJWT', # PyJWT wird als 'jwt' importiert
'dotenv': 'python-dotenv', # python-dotenv wird als 'dotenv' importiert
'gunicorn': 'gunicorn'
}
missing_packages = []
for package in required_packages:
for import_name, package_name in required_packages.items():
try:
__import__(package)
print(f"{package}")
__import__(import_name)
print(f"{package_name}")
except ImportError:
print(f"{package} fehlt")
missing_packages.append(package)
print(f"{package_name} fehlt")
missing_packages.append(package_name)
if missing_packages:
print(f" Fehlende Pakete: {', '.join(missing_packages)}")
print(" Installiere mit: pip install -r requirements.txt")
return False
else:
print(" ✅ Alle Dependencies verfügbar")
return True
@ -80,26 +82,29 @@ def test_configuration():
print(f" ❌ Konfigurationsfehler: {e}")
return False
def test_app_factory():
def test_application_factory():
"""Teste Application Factory Pattern"""
print("🏭 Teste Application Factory...")
try:
# Temporäre Umgebungsvariablen setzen
os.environ['SECRET_KEY'] = 'test_secret_key'
os.environ['DATABASE_PATH'] = ':memory:'
from app import create_app
# Teste verschiedene Konfigurationen
dev_app = create_app('development')
prod_app = create_app('production')
test_app = create_app('testing')
configs = ['development', 'production', 'testing']
print(f" ✅ Development-App: {dev_app.config['FLASK_ENV']}")
print(f" ✅ Production-App: {prod_app.config['FLASK_ENV']}")
print(f" ✅ Testing-App: {test_app.config['FLASK_ENV']}")
for config_name in configs:
try:
app = create_app(config_name)
if app and hasattr(app, 'config'):
print(f"{config_name.title()}-Config erfolgreich geladen")
else:
print(f"{config_name.title()}-Config fehlgeschlagen")
return False
except Exception as e:
print(f"{config_name.title()}-Config Fehler: {e}")
return False
print(" ✅ Application Factory funktioniert")
return True
except Exception as e:
@ -204,8 +209,8 @@ def test_health_endpoint():
app = create_app('testing')
with app.test_client() as client:
# Teste sowohl /health als auch /monitoring/health
endpoints_to_test = ['/health', '/monitoring/health']
# Teste sowohl /health als auch /monitoring/health und /monitoring/health/simple
endpoints_to_test = ['/health', '/monitoring/health/simple', '/monitoring/health']
for endpoint in endpoints_to_test:
response = client.get(endpoint)
@ -244,7 +249,7 @@ def main():
test_python_environment,
test_dependencies,
test_configuration,
test_app_factory,
test_application_factory,
test_database_functions,
test_environment_variables,
test_wsgi,