Files
Random-Word-API/main.py
jafreli b348d11764
Some checks failed
Build and Push Docker Image / build (push) Failing after 48s
undate Docker + workflows
2025-11-19 14:27:38 +01:00

44 lines
1.4 KiB
Python

import sqlite3
import os
from fastapi import FastAPI
# 📁 Konfiguration: Lese Pfad aus ENV oder nutze Standard
# Im Docker Container setzen wir dies später auf /app/data/hangman.db
DB_PATH = os.getenv("DB_PATH", "hangman.db")
# 🛠️ Datenbank-Hilfsfunktionen
def get_db_connection():
"""Erstellt eine Verbindung zur SQLite-Datenbank."""
# Prüfen, ob das Verzeichnis existiert, falls es ein absoluter Pfad ist
directory = os.path.dirname(DB_PATH)
if directory and not os.path.exists(directory):
os.makedirs(directory, exist_ok=True)
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
# 💡 Initialisiere die FastAPI-Anwendung
app = FastAPI()
@app.get("/random_word")
def get_random_word():
"""
Holt ein zufälliges Wort direkt aus der SQL-Datenbank.
"""
try:
conn = get_db_connection()
cursor = conn.cursor()
# SQL-Magie: Wählt zufällig eine Zeile aus der Datenbank
cursor.execute('SELECT word FROM words ORDER BY RANDOM() LIMIT 1')
result = cursor.fetchone()
conn.close()
if result:
return {"word": result["word"]}
else:
return {"error": f"Keine Wörter in {DB_PATH} gefunden."}
except sqlite3.OperationalError as e:
return {"error": f"Datenbankfehler bei {DB_PATH}: {str(e)}"}