Quelle:
Zitatsdatenbank erstellen#
Unten eine kompakte Schritt‑für‑Schritt‑Anleitung vom leeren Verzeichnis bis zum laufenden Container mit Quotes‑App, API und HTML‑Frontend.
1. Projektstruktur anlegen#
In einem neuen Ordner, z.B. quotes-app/:
quotes-app/
app.py
models.py
schemas.py
database.py
deps.py
requirements.txt
Dockerfile
static/
index.html2. models.py – SQLAlchemy‑Model#
# models.py
from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, Text
from sqlalchemy.orm import declarative_base
Base = declarative_base()
class Quote(Base):
__tablename__ = "quotes"
id = Column(Integer, primary_key=True, index=True)
text = Column(Text, nullable=False)
author = Column(String(255), nullable=True, index=True)
source = Column(String(255), nullable=True)
language = Column(String(10), nullable=True, index=True)
tags = Column(String(255), nullable=True, index=True) # "tag1,tag2"
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
updated_at = Column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
)
created_by = Column(String(255), nullable=True, index=True)3. schemas.py – Pydantic‑Schemas#
# schemas.py
from datetime import datetime
from typing import Optional, List
from pydantic import BaseModel
class QuoteBase(BaseModel):
text: str
author: Optional[str] = None
source: Optional[str] = None
language: Optional[str] = "de"
tags: Optional[list[str]] = None
class QuoteCreate(QuoteBase):
pass
class QuoteUpdate(BaseModel):
text: Optional[str] = None
author: Optional[str] = None
source: Optional[str] = None
language: Optional[str] = None
tags: Optional[list[str]] = None
class QuoteOut(QuoteBase):
id: int
created_at: datetime
updated_at: datetime
created_by: Optional[str] = None
class Config:
from_attributes = True4. database.py – Engine & Session#
# database.py
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import Base
DB_PATH = os.getenv("QUOTES_DB", "./quotes.db")
DATABASE_URL = f"sqlite:///{DB_PATH}"
engine = create_engine(
DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def init_db():
Base.metadata.create_all(bind=engine)5. deps.py – DB‑Dependency & API‑Key‑Auth#
# deps.py
import os
from fastapi import Depends, HTTPException, Security
from fastapi.security.api_key import APIKeyHeader
from sqlalchemy.orm import Session
from database import SessionLocal
API_KEY = os.getenv("API_KEY", "changeme")
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def get_api_key(api_key: str = Security(api_key_header)):
if api_key != API_KEY:
raise HTTPException(status_code=401, detail="Invalid or missing API key")
return api_key6. app.py – FastAPI‑App, API, QotD, Webhook, Static#
# app.py
from datetime import date
from typing import List, Optional
from fastapi import Depends, FastAPI, HTTPException, Query
from fastapi.responses import JSONResponse, PlainTextResponse
from fastapi.staticfiles import StaticFiles
from sqlalchemy.orm import Session
from sqlalchemy.sql import func
from database import init_db
from deps import get_db, get_api_key
from models import Quote
from schemas import QuoteCreate, QuoteOut, QuoteUpdate
app = FastAPI(title="Quotes API")
# Static Frontend
app.mount("/", StaticFiles(directory="static", html=True), name="static")
@app.on_event("startup")
def on_startup():
init_db()
def _tags_to_str(tags: Optional[list[str]]) -> str | None:
if not tags:
return None
return ",".join(sorted({t.strip() for t in tags if t.strip()}))
def _str_to_tags(s: Optional[str]) -> list[str] | None:
if not s:
return None
return [t.strip() for t in s.split(",") if t.strip()]
@app.get("/api/quotes", response_model=List[QuoteOut])
def list_quotes(
q: Optional[str] = Query(None, description="Volltextsuche im Zitat"),
author: Optional[str] = None,
tag: Optional[str] = None,
limit: int = 50,
db: Session = Depends(get_db),
):
query = db.query(Quote)
if q:
like = f"%{q}%"
query = query.filter(Quote.text.ilike(like))
if author:
query = query.filter(Quote.author == author)
if tag:
query = query.filter(Quote.tags.ilike(f"%{tag}%"))
query = query.order_by(Quote.created_at.desc()).limit(limit)
results = query.all()
for r in results:
r.tags = _str_to_tags(r.tags)
return results
@app.get("/api/quotes/{quote_id}", response_model=QuoteOut)
def get_quote(quote_id: int, db: Session = Depends(get_db)):
quote = db.query(Quote).get(quote_id)
if not quote:
raise HTTPException(status_code=404, detail="Quote not found")
quote.tags = _str_to_tags(quote.tags)
return quote
@app.get("/api/quotes/random", response_model=QuoteOut)
def get_random_quote(
tag: Optional[str] = None,
db: Session = Depends(get_db),
):
query = db.query(Quote)
if tag:
query = query.filter(Quote.tags.ilike(f"%{tag}%"))
quote = query.order_by(func.random()).first()
if not quote:
raise HTTPException(status_code=404, detail="No quote found")
quote.tags = _str_to_tags(quote.tags)
return quote
@app.post("/api/quotes", response_model=QuoteOut, dependencies=[Depends(get_api_key)])
def create_quote(
payload: QuoteCreate,
db: Session = Depends(get_db),
):
quote = Quote(
text=payload.text,
author=payload.author,
source=payload.source,
language=payload.language,
tags=_tags_to_str(payload.tags),
created_by="api",
)
db.add(quote)
db.commit()
db.refresh(quote)
quote.tags = _str_to_tags(quote.tags)
return quote
@app.put("/api/quotes/{quote_id}", response_model=QuoteOut, dependencies=[Depends(get_api_key)])
def update_quote(
quote_id: int,
payload: QuoteUpdate,
db: Session = Depends(get_db),
):
quote = db.query(Quote).get(quote_id)
if not quote:
raise HTTPException(status_code=404, detail="Quote not found")
if payload.text is not None:
quote.text = payload.text
if payload.author is not None:
quote.author = payload.author
if payload.source is not None:
quote.source = payload.source
if payload.language is not None:
quote.language = payload.language
if payload.tags is not None:
quote.tags = _tags_to_str(payload.tags)
db.commit()
db.refresh(quote)
quote.tags = _str_to_tags(quote.tags)
return quote
@app.delete("/api/quotes/{quote_id}", status_code=204, dependencies=[Depends(get_api_key)])
def delete_quote(
quote_id: int,
db: Session = Depends(get_db),
):
quote = db.query(Quote).get(quote_id)
if not quote:
raise HTTPException(status_code=404, detail="Quote not found")
db.delete(quote)
db.commit()
return
# Quote of the Day (deterministisch pro Datum)
@app.get("/api/quotes/qotd", response_model=QuoteOut)
def get_quote_of_the_day(
day: date | None = None,
db: Session = Depends(get_db),
):
if day is None:
day = date.today()
total = db.query(func.count(Quote.id)).scalar()
if not total:
raise HTTPException(status_code=404, detail="No quote available")
idx = (day.toordinal() % total)
quote = (
db.query(Quote)
.order_by(Quote.id)
.offset(idx)
.limit(1)
.first()
)
if not quote:
raise HTTPException(status_code=404, detail="No quote found")
quote.tags = _str_to_tags(quote.tags)
return quote
# QotD-Webhooks
@app.get("/api/quotes/qotd/webhook")
def get_quote_of_the_day_webhook(
day: date | None = None,
format: str = "generic",
db: Session = Depends(get_db),
):
if day is None:
day = date.today()
total = db.query(func.count(Quote.id)).scalar()
if not total:
raise HTTPException(status_code=404, detail="No quote available")
idx = (day.toordinal() % total)
quote = (
db.query(Quote)
.order_by(Quote.id)
.offset(idx)
.limit(1)
.first()
)
if not quote:
raise HTTPException(status_code=404, detail="No quote found")
tags = _str_to_tags(quote.tags)
text = f"\"{quote.text}\""
if quote.author:
text += f" — {quote.author}"
if quote.source:
text += f" ({quote.source})"
if format == "generic":
return JSONResponse(
{"text": text, "language": quote.language, "tags": tags,
"id": quote.id, "date": str(day)}
)
if format in ("slack", "mattermost"):
return JSONResponse({"text": text})
if format == "discord":
return JSONResponse({"content": text})
if format == "plain":
return PlainTextResponse(text)
return JSONResponse(
{"text": text, "language": quote.language, "tags": tags,
"id": quote.id, "date": str(day)}
)7. static/index.html – HTML‑Frontend (inkl. CRUD + QotD)#
Nimm die Version mit Suche, Neu‑Anlage, Edit‑Overlay, Löschen, Random, QotD:
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>Quotes App</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
rel="stylesheet"
>
<style>
body { padding-top: 2rem; }
textarea { min-height: 100px; }
.quote-card { margin-bottom: 1rem; }
.tag-badge { margin-right: 0.25rem; }
</style>
</head>
<body class="bg-light">
<div class="container">
<h1 class="mb-4">Quotes App</h1>
<!-- Suche / Filter -->
<div class="card mb-4">
<div class="card-body">
<h5 class="card-title">Suche</h5>
<div class="row g-2">
<div class="col-md-4">
<input id="searchText" class="form-control" placeholder="Volltextsuche">
</div>
<div class="col-md-3">
<input id="searchAuthor" class="form-control" placeholder="Autor">
</div>
<div class="col-md-3">
<input id="searchTag" class="form-control" placeholder="Tag">
</div>
<div class="col-md-2 d-grid">
<button id="btnSearch" class="btn btn-primary">Suchen</button>
</div>
</div>
<div class="mt-3">
<button id="btnRandom" class="btn btn-outline-secondary btn-sm">
Zufälliges Zitat
</button>
<button id="btnQotd" class="btn btn-outline-info btn-sm ms-2">
Quote of the Day
</button>
</div>
</div>
</div>
<!-- Neues Zitat -->
<div class="card mb-4">
<div class="card-body">
<h5 class="card-title">Neues Zitat</h5>
<div class="mb-3">
<label class="form-label">Zitat</label>
<textarea id="newText" class="form-control"></textarea>
</div>
<div class="row g-2 mb-3">
<div class="col-md-4">
<label class="form-label">Autor</label>
<input id="newAuthor" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Quelle</label>
<input id="newSource" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Sprache</label>
<input id="newLang" class="form-control" value="de">
</div>
</div>
<div class="mb-3">
<label class="form-label">Tags (kommagetrennt)</label>
<input id="newTags" class="form-control" placeholder="inspiration, metal, humor">
</div>
<div class="mb-3">
<label class="form-label">API-Key</label>
<input id="apiKey" class="form-control" placeholder="X-API-Key für Schreibvorgänge">
</div>
<button id="btnCreate" class="btn btn-success">Speichern</button>
<span id="createStatus" class="ms-3 text-muted"></span>
</div>
</div>
<!-- Ergebnisliste -->
<div id="quotesList"></div>
</div>
<!-- Edit-Overlay -->
<div id="editOverlay" class="position-fixed top-0 start-0 w-100 h-100 bg-dark bg-opacity-50 d-none">
<div class="d-flex justify-content-center align-items-center h-100">
<div class="card" style="max-width: 700px; width: 100%; margin: 1rem;">
<div class="card-body">
<h5 class="card-title">Zitat bearbeiten</h5>
<input type="hidden" id="editId">
<div class="mb-3">
<label class="form-label">Zitat</label>
<textarea id="editText" class="form-control"></textarea>
</div>
<div class="row g-2 mb-3">
<div class="col-md-4">
<label class="form-label">Autor</label>
<input id="editAuthor" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Quelle</label>
<input id="editSource" class="form-control">
</div>
<div class="col-md-4">
<label class="form-label">Sprache</label>
<input id="editLang" class="form-control">
</div>
</div>
<div class="mb-3">
<label class="form-label">Tags (kommagetrennt)</label>
<input id="editTags" class="form-control">
</div>
<div class="mb-3">
<label class="form-label">API-Key</label>
<input id="editApiKey" class="form-control" placeholder="X-API-Key">
</div>
<div class="d-flex justify-content-end">
<button class="btn btn-secondary me-2" onclick="closeEdit()">Abbrechen</button>
<button class="btn btn-primary" onclick="saveEdit()">Speichern</button>
</div>
<div id="editStatus" class="mt-2 text-muted"></div>
</div>
</div>
</div>
</div>
<script>
const API_BASE = ""; // gleicher Host/Port
function tagsToBadges(tags) {
if (!tags || !tags.length) return "";
return tags.map(t =>
`<span class="badge bg-secondary tag-badge">${t}</span>`
).join(" ");
}
function renderQuotes(quotes) {
const container = document.getElementById("quotesList");
if (!quotes || !quotes.length) {
container.innerHTML = "<p>Keine Zitate gefunden.</p>";
return;
}
container.innerHTML = quotes.map(q => `
<div class="card quote-card" data-id="${q.id}">
<div class="card-body">
<blockquote class="blockquote mb-2">
<p>${q.text.replace(/\n/g, "<br>")}</p>
</blockquote>
<footer class="blockquote-footer">
${q.author || "Unbekannt"}
${q.source ? `, <cite>${q.source}</cite>` : ""}
</footer>
<div class="mt-2 d-flex justify-content-between align-items-center">
<div>
${tagsToBadges(q.tags)}
<span class="text-muted small">[${q.language || ""}] #${q.id}</span>
</div>
<div>
<button class="btn btn-sm btn-outline-primary me-2" onclick="openEdit(${q.id})">
Bearbeiten
</button>
<button class="btn btn-sm btn-outline-danger" onclick="deleteQuote(${q.id})">
Löschen
</button>
</div>
</div>
</div>
</div>
`).join("");
}
async function fetchQuotes() {
const q = document.getElementById("searchText").value.trim();
const author = document.getElementById("searchAuthor").value.trim();
const tag = document.getElementById("searchTag").value.trim();
const params = new URLSearchParams();
if (q) params.append("q", q);
if (author) params.append("author", author);
if (tag) params.append("tag", tag);
const url = API_BASE + "/api/quotes" + (params.toString() ? `?${params.toString()}` : "");
const res = await fetch(url);
if (!res.ok) {
alert("Fehler beim Laden der Zitate");
return;
}
const data = await res.json();
renderQuotes(data);
}
async function fetchRandomQuote() {
const tag = document.getElementById("searchTag").value.trim();
const params = new URLSearchParams();
if (tag) params.append("tag", tag);
const url = API_BASE + "/api/quotes/random" + (params.toString() ? `?${params.toString()}` : "");
const res = await fetch(url);
if (!res.ok) {
alert("Kein zufälliges Zitat gefunden");
return;
}
const data = await res.json();
renderQuotes([data]);
}
async function fetchQuoteOfTheDay() {
const res = await fetch(API_BASE + "/api/quotes/qotd");
if (!res.ok) {
alert("Kein Quote of the Day verfügbar");
return;
}
const data = await res.json();
renderQuotes([data]);
}
async function createQuote() {
const statusEl = document.getElementById("createStatus");
statusEl.textContent = "";
const text = document.getElementById("newText").value.trim();
if (!text) {
alert("Zitattext darf nicht leer sein");
return;
}
const author = document.getElementById("newAuthor").value.trim() || null;
const source = document.getElementById("newSource").value.trim() || null;
const language = document.getElementById("newLang").value.trim() || "de";
const tagsStr = document.getElementById("newTags").value.trim();
const apiKey = document.getElementById("apiKey").value.trim();
const tags = tagsStr ? tagsStr.split(",").map(t => t.trim()).filter(Boolean) : [];
const payload = { text, author, source, language, tags };
const res = await fetch(API_BASE + "/api/quotes", {
method: "POST",
headers: {
"Content-Type": "application/json",
...(apiKey ? { "X-API-Key": apiKey } : {})
},
body: JSON.stringify(payload)
});
if (!res.ok) {
statusEl.textContent = "Fehler beim Speichern";
statusEl.className = "text-danger";
return;
}
statusEl.textContent = "Gespeichert";
statusEl.className = "text-success";
document.getElementById("newText").value = "";
document.getElementById("newAuthor").value = "";
document.getElementById("newSource").value = "";
document.getElementById("newLang").value = "de";
document.getElementById("newTags").value = "";
fetchQuotes();
}
async function fetchQuoteById(id) {
const res = await fetch(API_BASE + "/api/quotes/" + id);
if (!res.ok) {
throw new Error("Zitat nicht gefunden");
}
return await res.json();
}
async function openEdit(id) {
try {
const q = await fetchQuoteById(id);
document.getElementById("editId").value = q.id;
document.getElementById("editText").value = q.text;
document.getElementById("editAuthor").value = q.author || "";
document.getElementById("editSource").value = q.source || "";
document.getElementById("editLang").value = q.language || "de";
document.getElementById("editTags").value = (q.tags || []).join(", ");
document.getElementById("editStatus").textContent = "";
document.getElementById("editOverlay").classList.remove("d-none");
} catch (e) {
alert(e.message || "Fehler beim Laden des Zitats");
}
}
function closeEdit() {
document.getElementById("editOverlay").classList.add("d-none");
}
async function saveEdit() {
const id = document.getElementById("editId").value;
const statusEl = document.getElementById("editStatus");
statusEl.textContent = "";
const text = document.getElementById("editText").value.trim();
if (!text) {
alert("Zitattext darf nicht leer sein");
return;
}
const author = document.getElementById("editAuthor").value.trim() || null;
const source = document.getElementById("editSource").value.trim() || null;
const language = document.getElementById("editLang").value.trim() || "de";
const tagsStr = document.getElementById("editTags").value.trim();
const apiKey = document.getElementById("editApiKey").value.trim() ||
document.getElementById("apiKey").value.trim();
const tags = tagsStr ? tagsStr.split(",").map(t => t.trim()).filter(Boolean) : [];
const payload = { text, author, source, language, tags };
const res = await fetch(API_BASE + "/api/quotes/" + id, {
method: "PUT",
headers: {
"Content-Type": "application/json",
...(apiKey ? { "X-API-Key": apiKey } : {})
},
body: JSON.stringify(payload)
});
if (!res.ok) {
statusEl.textContent = "Fehler beim Speichern";
statusEl.className = "text-danger";
return;
}
statusEl.textContent = "Gespeichert";
statusEl.className = "text-success";
await fetchQuotes();
closeEdit();
}
async function deleteQuote(id) {
const apiKey = document.getElementById("apiKey").value.trim();
if (!apiKey) {
alert("Bitte API-Key im neuen-Zitat-Formular eintragen (für Löschvorgänge).");
return;
}
if (!confirm("Zitat #" + id + " wirklich löschen?")) {
return;
}
const res = await fetch(API_BASE + "/api/quotes/" + id, {
method: "DELETE",
headers: {
"X-API-Key": apiKey
}
});
if (!res.ok) {
alert("Fehler beim Löschen");
return;
}
fetchQuotes();
}
document.getElementById("btnSearch").addEventListener("click", fetchQuotes);
document.getElementById("btnRandom").addEventListener("click", fetchRandomQuote);
document.getElementById("btnQotd").addEventListener("click", fetchQuoteOfTheDay);
document.getElementById("btnCreate").addEventListener("click", createQuote);
// Initial
fetchQuotes();
</script>
</body>
</html>8. requirements.txt#
fastapi
uvicorn[standard]
sqlalchemy
pydantic9. Dockerfile – Container bauen#
FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
ENV QUOTES_DB=/data/quotes.db
ENV API_KEY=changeme
VOLUME ["/data"]
EXPOSE 8000
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]10. Container mit Podman bauen und starten#
cd quotes-app
podman build -t quotes-app:latest .
podman volume create quotes-data
podman run -d \
--name quotes-app \
-p 8080:8000 \
-v quotes-data:/data \
-e API_KEY="supersecret-123" \
quotes-app:latest- Frontend & API:
http://<host>:8080/ - API‑Dokumentation:
http://<host>:8080/docs - QotD‑Webhook plain text:
http://<host>:8080/api/quotes/qotd/webhook?format=plain
Wenn du willst, folgt als nächstes ein kleines Beispiel‑Script, das deinen QotD täglich in einen Chat (z.B. Matrix oder Discord) pusht.
