- FastAPI + SQLite backend with REST API - Polymorphic Media model (book + series) - Cover lookup via Open Library - Vanilla HTML/CSS/JS frontend (MAL-inspired) - Dark theme, status tabs, drawer detail, stats modal - 8 seed demo entries
46 lines
1.2 KiB
Python
46 lines
1.2 KiB
Python
"""Datenbank-Engine und Session-Verwaltung."""
|
||
from __future__ import annotations
|
||
|
||
from pathlib import Path
|
||
|
||
from sqlalchemy import create_engine
|
||
from sqlalchemy.orm import DeclarativeBase, sessionmaker
|
||
|
||
# SQLite-Datei liegt im data/-Ordner (gitignored).
|
||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||
DATA_DIR = BASE_DIR / "data"
|
||
DATA_DIR.mkdir(exist_ok=True)
|
||
DB_PATH = DATA_DIR / "watchstack.db"
|
||
|
||
DATABASE_URL = f"sqlite:///{DB_PATH}"
|
||
|
||
engine = create_engine(
|
||
DATABASE_URL,
|
||
echo=False,
|
||
future=True,
|
||
connect_args={"check_same_thread": False},
|
||
)
|
||
|
||
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False)
|
||
|
||
|
||
class Base(DeclarativeBase):
|
||
"""Basisklasse für alle ORM-Modelle."""
|
||
|
||
|
||
def get_db():
|
||
"""FastAPI-Dependency: liefert eine Session, schließt sie danach."""
|
||
db = SessionLocal()
|
||
try:
|
||
yield db
|
||
finally:
|
||
db.close()
|
||
|
||
|
||
def init_db() -> None:
|
||
"""Erstellt alle Tabellen, falls noch nicht vorhanden."""
|
||
# noqa: F401 – Modelle müssen importiert sein, damit sie bei Base.metadata registriert sind.
|
||
from app import models # type: ignore[F401]
|
||
|
||
Base.metadata.create_all(bind=engine)
|