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.
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.