Ein umfassendes Lernprojekt fĂźr den Kurs "Relationale Datenbanken" der HĂśheren Fachschule fĂźr Technik Mittelland zur praktischen Demonstration von Object Relational Mapping (ORM) mit modernen Python-Technologien.
đ Kurs-Website
Dieses Projekt vermittelt Studierenden folgende Kernkonzepte:
- Object Relational Mapping (ORM) mit SQLAlchemy
- FastAPI Fundamentals - Asynchrone APIs, Dependency Injection, Auto-Dokumentation
- Clean Architecture - Separation of Concerns zwischen Model-, Schema-, Service- und Router-Schichten
- Datenbankmanagement - PostgreSQL Integration, Alembic Migrationen
- Containerisierte Entwicklung - Docker Compose fĂźr lokale Umgebung
- Type-Safe Development - Pydantic fĂźr sichere Datenvalidierung
- FastAPI - Modernes, schnelles Web-Framework
- Python 3.11+ - Moderne Python-Features und Performance
- SQLAlchemy 2.0 - Object Relational Mapping
- PostgreSQL 17 - Relationale Datenbank
- Alembic - Datenbankmigrationen
- Jinja2 - Server-side HTML Templating
- Bootstrap CSS - Responsive Web Design
- UV - Blitzschnelles Package Management
- Pytest - Testing Framework
- Docker Compose - Lokale Entwicklungsumgebung
- Python 3.11 oder hĂśher (Python.org)
- UV fĂźr Package Management (Installation)
- Docker & Docker Compose fĂźr die Datenbankumgebung
- Git fĂźr Versionskontrolle
git clone <repository-url>
cd notes-app
# PostgreSQL Datenbank mit Docker Compose starten
docker-compose -f docker-compose.db.yaml up -d
# ĂberprĂźfen, ob die Datenbank läuft
docker ps
# Dependencies mit UV installieren
uv sync
# Umgebungsvariablen konfigurieren
cp .env.example .env
# Anwendung starten
uv run python -m app.main
# Alternative: Mit uvicorn direkt
uv run uvicorn app.main:app --reload
- Webanwendung: http://localhost:8000
- API Dokumentation: http://localhost:8000/docs
- Datenbank: PostgreSQL auf localhost:5432
- Database:
notesapp
- Username:
notesapp
- Password:
notesapp
- Database:
Das Projekt folgt einer Layered Architecture mit klarer Trennung der Verantwortlichkeiten:
app/
âââ routers/ # đ Presentation Layer
â âââ web.py # Web UI Endpoints
â âââ api.py # REST API Endpoints
âââ services/ # đź Business Logic Layer
â âââ note_service.py # Geschäftslogik & Datenbankoperationen
âââ schemas/ # đ Data Transfer Objects
â âââ note.py # Pydantic Schemas fĂźr Validierung
âââ models/ # đž Data Model Layer
â âââ note.py # SQLAlchemy ORM Models
âââ database.py # đ§ Datenbankverbindung
âââ config.py # âď¸ Konfigurationsmanagement
âââ main.py # đ Application Factory
HTTP Request â Router â Service â SQLAlchemy â Database
â
Schema/DTO â Pydantic â Model â SQLAlchemy
# SQLAlchemy Model (Datenbankrepräsentation)
class Note(Base):
__tablename__ = "notes"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
title = Column(String(100), nullable=False)
content = Column(Text, nullable=False)
created_at = Column(DateTime, server_default=func.now())
updated_at = Column(DateTime, onupdate=func.now())
# Pydantic Schema fĂźr Datenvalidierung
class NoteCreate(BaseModel):
title: str = Field(..., min_length=1, max_length=100)
content: str = Field(..., min_length=1)
class NoteResponse(BaseModel):
id: UUID
title: str
content: str
created_at: datetime
updated_at: Optional[datetime]
model_config = ConfigDict(from_attributes=True)
class NoteService:
def __init__(self, db: Session = Depends(get_db)):
self.db = db
async def create_note(self, note_data: NoteCreate) -> Note:
note = Note(**note_data.model_dump())
self.db.add(note)
self.db.commit()
self.db.refresh(note)
return note
@router.post("/notes", response_model=NoteResponse)
async def create_note(
note_data: NoteCreate,
service: NoteService = Depends()
):
return await service.create_note(note_data)
uv run pytest tests/unit -v
uv run pytest tests/integration -v
uv run pytest --cov=app --cov-report=html
# Report verfĂźgbar unter: htmlcov/index.html
- CRUD Operationen verstehen - Analysiere die vollständigen Create/Read/Update/Delete Workflows
- Schema-Validierung erkunden - Untersuche, wie Pydantic Eingabedaten validiert
- ORM-Queries schreiben - Verstehe SQLAlchemy Query-Syntax und Filteroperationen
- Neue Entität hinzufßgen - Erstelle eine
Tag
Entität mit Many-to-Many Beziehung zuNote
- Erweiterte Validierung - FĂźge Custom Validators in Pydantic Schemas hinzu
- Suchoption einbauen - Implementiere Volltextsuche in Notizen
- Pagination hinzufĂźgen - Erweitere die API um Seitennummerierung
- Asynchrone Datenbankoperationen - Migriere zu async SQLAlchemy
- Caching implementieren - FĂźge Redis-basiertes Caching hinzu
- Background Tasks - Implementiere asynchrone Aufgaben mit Celery
- API Versionierung - Erstelle versionierte API Endpoints
Datei | Zweck | Lernfokus |
---|---|---|
models/note.py |
SQLAlchemy Model | ORM Mapping, Relationships |
schemas/note.py |
Pydantic Schemas | Datenvalidierung, Serialisierung |
services/note_service.py |
Business Logic | Service Pattern, Transaktionen |
routers/api.py |
REST API | FastAPI Routing, Dependencies |
routers/web.py |
Web UI | Template Rendering, Forms |
config.py |
Konfiguration | Settings Management |
alembic/ |
Migrationen | Datenbankevolution |
Das Projekt nutzt Docker Compose fĂźr eine konsistente Entwicklungsumgebung:
# docker-compose.db.yaml
services:
postgres:
image: postgres:17
environment:
POSTGRES_DB: notesapp
POSTGRES_USER: notesapp
POSTGRES_PASSWORD: notesapp
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
# Datenbank starten
docker-compose -f docker-compose.db.yaml up -d
# Logs anzeigen
docker-compose -f docker-compose.db.yaml logs -f
# Datenbank stoppen
docker-compose -f docker-compose.db.yaml down
# Datenbank zurĂźcksetzen
docker-compose -f docker-compose.db.yaml down -v
Dieses Projekt dient Bildungszwecken. Verbesserungsvorschläge und Erweiterungen sind willkommen:
- Fork des Repositories erstellen
- Feature Branch erstellen (
git checkout -b feature/neue-funktion
) - Ănderungen committen (
git commit -am 'FĂźge neue Funktion hinzu'
) - Branch pushen (
git push origin feature/neue-funktion
) - Pull Request erstellen
Dieses Projekt steht unter der MIT-Lizenz und dient ausschliesslich Bildungszwecken im Rahmen des Kurses "Relationale Datenbanken" der HĂśheren Fachschule fĂźr Technik Mittelland.