Spaces:
Configuration error
Configuration error
Upload 38 files
Browse filesFiles changed (38)
- .env.exampleAdded+4
- .pytest_cache/.gitignoreAdded+2
- .pytest_cache/CACHEDIR.TAGAdded+4
- .pytest_cache/README.mdAdded+8
- .pytest_cache/v/cache/lastfailedAdded+1
- .pytest_cache/v/cache/nodeidsAdded+6
- DockerfileAdded+41
- README.md+118-10
- app/__init__.pyAdded+1
- app/__pycache__/__init__.cpython-313.pycAdded
- app/__pycache__/cache.cpython-313.pycAdded
- app/__pycache__/config.cpython-313.pycAdded
- app/__pycache__/fetcher.cpython-313.pycAdded
- app/__pycache__/main.cpython-313.pycAdded
- app/__pycache__/metrics.cpython-313.pycAdded
- app/__pycache__/models.cpython-313.pycAdded
- app/cache.pyAdded+72
- app/config.pyAdded+37
- app/fetcher.pyAdded+283
- app/main.pyAdded+239
- app/metrics.pyAdded+44
- app/models.pyAdded+105
- app/static/app.jsAdded+256
- app/static/styles.cssAdded+331
- app/templates/index.html.j2Added+106
- data/.gitkeepAdded+1
- data/cache.jsonAdded+290
- docker-compose.ymlAdded+15
- pyproject.tomlAdded+63
- rheinpegel_app.egg-info/PKG-INFOAdded+139
- rheinpegel_app.egg-info/SOURCES.txtAdded+19
- rheinpegel_app.egg-info/dependency_links.txtAdded+1
- rheinpegel_app.egg-info/requires.txtAdded+17
- rheinpegel_app.egg-info/top_level.txtAdded+1
- tests/__pycache__/test_endpoints.cpython-313-pytest-8.4.1.pycAdded
- tests/__pycache__/test_parser.cpython-313-pytest-8.4.1.pycAdded
- tests/test_endpoints.pyAdded+77
- tests/test_parser.pyAdded+58
1234SOURCE_URL=https://www.stadt-koeln.de/interne-dienste/hochwasser/pegel_ws.php
REFRESH_SECONDS=120
TZ=Europe/Berlin
PORT=800012# Created by pytest automatically.
*1234Signature: 8a477f597d28d172789f06886806bc55# This file is a cache directory tag created by pytest.# For information about cache directory tags, see:# https://bford.info/cachedir/spec.html12345678# pytest cache directory #
This directory contains data from the pytest's cache plugin,
which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
**Do not** commit this to version control.
See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.1{}123456[
"tests/test_endpoints.py::test_api_history_returns_entries",
"tests/test_endpoints.py::test_api_latest_returns_measurement",
"tests/test_parser.py::test_parse_json_payload",
"tests/test_parser.py::test_parse_xml_payload"
]1234567891011121314151617181920212223242526272829303132333435363738394041FROM python:3.11-slim
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
WORKDIR /app
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
COPY pyproject.toml ./
RUN pip install --no-cache-dir --upgrade pip \
&& pip install --no-cache-dir \
fastapi>=0.111 \
"uvicorn[standard]>=0.29" \
httpx>=0.27 \
python-dotenv>=1.0 \
jinja2>=3.1 \
pydantic>=2.7 \
pydantic-settings>=2.4 \
prometheus-client>=0.20 \
python-dateutil>=2.9 \
defusedxml>=0.7
COPY app ./app
COPY data ./data
COPY README.md ./
COPY .env.example ./
RUN adduser --system --group appuser \
&& chown -R appuser:appuser /app
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 CMD curl -fsS http://localhost:8000/healthz || exit 1
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]12345678910---title: Rheinpegel Pythonemoji: 👀colorFrom: graycolorTo: bluesdk: dockerpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118<<<<<<< HEAD# rheinpegel-python-app=======# Rheinpegel AppEine moderne FastAPI-Anwendung, die den aktuellen Rheinpegel (Köln) abruft, zwischenspeichert und visuell aufbereitet. Die Anwendung kombiniert serverseitiges Polling mit einem reaktiven Frontend (AJAX, Countdown, Sparkline) und liefert zusätzlich Status- sowie Prometheus-Kennzahlen.## Hauptfunktionen- **Asynchrones Polling** der offiziellen Quelle via `httpx` mit Timeout (8 s) und exponentiellem Backoff (4 Versuche).- **Automatische Format-Erkennung** für JSON oder XML und robuste Feldzuordnung.- **Trend-Berechnung** aus Rohdaten oder anhand der letzten Messwerte (Δ > 2 cm ⇒ ↑, Δ < −2 ⇒ ↓).- **Mehrstufiges Caching**: In-Memory-Ringpuffer (48 Werte) + JSON-Persistenz unter `data/cache.json`.- **Demo-Modus** bei Netzwerkfehlern oder via `?demo=1` mit synthetischen, plausiblen Messwerten.- **FastAPI + Jinja2** Dashboard mit responsive Karte, Warnstufen, Sparkline (Inline-SVG) sowie Auto-Refresh-Toggle und Countdown.- **Prometheus-Metriken**: letzte Latenz, Erfolgs-/Fehlerzähler, Datenalter und Health-Endpoint.## Voraussetzungen- Python 3.11+- Optional: [uv](https://github.com/astral-sh/uv) für schnelle virtuelle Umgebungen## Installation & Setup### Variante A: uv```bashuv venvsource .venv/bin/activate # Windows: .venv\Scripts\activateuv pip install -e .cp .env.example .env```### Variante B: pip / venv```bashpython -m venv .venvsource .venv/bin/activate # Windows: .venv\Scripts\activatepip install --upgrade pippip install -e .copy .env.example .env # Windows```> **Hinweis:** Die Umgebungsvariablen (.env) steuern u.a. den Polling-Intervall (`REFRESH_SECONDS`), die Quelle (`SOURCE_URL`) und die Zeitzone (`TZ`).## Starten der Anwendung```bashuvicorn app.main:app --reload# oderpython -m app.main```Die Oberfläche ist anschließend unter http://127.0.0.1:8000 erreichbar.## Wichtige Endpunkte| Route | Beschreibung ||-----------------|-------------------------------------------------|| `/` | Dashboard mit Live-Karte, Trend, Sparkline || `/api/latest` | Neueste Messung (JSON) + komplette Historie || `/api/history` | Maximal 48 Messpunkte aus dem Ringpuffer || `/healthz` | 200 OK, wenn der Hintergrund-Task aktiv ist || `/metrics` | Prometheus-kompatible Kennzahlen |### Demo-ModusAlle Endpunkte akzeptieren `?demo=1`, um synthetische Daten zu liefern und das UI als „Demo“ zu markieren.## Tests```bashpytest```Die Tests decken das Parsing (JSON/XML) sowie zentrale FastAPI-Endpunkte ab.## Docker```bashdocker build -t rheinpegel-app .docker run -p 8000:8000 --env-file .env rheinpegel-app```Oder via Compose:```bashdocker-compose up --build```Der Container läuft als Non-Root-User, besitzt einen Healthcheck (`/healthz`) und bindet `./data` für persistente Caches ein.## Beispiel systemd Unit (optional)```ini[Unit]Description=Rheinpegel AppAfter=network.target[Service]User=www-dataWorkingDirectory=/opt/rheinpegel-appEnvironmentFile=/opt/rheinpegel-app/.envExecStart=/opt/rheinpegel-app/.venv/bin/uvicorn app.main:app --host 0.0.0.0 --port 8000Restart=always[Install]WantedBy=multi-user.target```## Weiterentwicklung- UI-Optimierungen, z. B. zusätzliche Karten oder historische Auswertungen- Export in weitere Formate (CSV/ICS)- Alarm-Benachrichtigungen (E-Mail, Webhooks) basierend auf WarnstufenViel Spaß beim Ausprobieren der Rheinpegel-App!>>>>>>> 6c0a1e2 (Initial commit)
1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172from __future__ import annotations
import asyncio
import json
import logging
from collections import deque
from pathlib import Path
from typing import Deque
from .models import Measurement
logger = logging.getLogger(__name__)
class MeasurementCache:
def __init__(self, *, maxlen: int = 48, storage_path: Path | str = "data/cache.json") -> None:
self._buffer: Deque[Measurement] = deque(maxlen=maxlen)
self._lock = asyncio.Lock()
self._path = Path(storage_path)
self._path.parent.mkdir(parents=True, exist_ok=True)
self._load_from_disk()
def _load_from_disk(self) -> None:
if not self._path.exists():
return
try:
raw = json.loads(self._path.read_text("utf-8"))
except json.JSONDecodeError as exc:
logger.warning("Failed to read cache file %s: %s", self._path, exc)
return
if not isinstance(raw, list):
logger.warning("Invalid cache file format: expected list, got %s", type(raw))
return
for item in raw[-self._buffer.maxlen :]:
try:
measurement = Measurement.model_validate(item)
except Exception as exc: # noqa: BLE001
logger.debug("Skipping invalid cache entry %s: %s", item, exc)
continue
self._buffer.append(measurement)
logger.info("Loaded %s cached measurements", len(self._buffer))
def _dump_to_disk(self) -> None:
data = [m.model_dump(mode="json") for m in self._buffer]
tmp_path = self._path.with_suffix(".tmp")
tmp_path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
tmp_path.replace(self._path)
async def add(self, measurement: Measurement, *, persist: bool = True) -> None:
async with self._lock:
latest = self._buffer[-1] if self._buffer else None
if latest and latest.timestamp == measurement.timestamp:
self._buffer.pop()
self._buffer.append(measurement)
if persist:
await asyncio.to_thread(self._dump_to_disk)
async def get_latest(self) -> Measurement | None:
async with self._lock:
return self._buffer[-1] if self._buffer else None
async def get_history(self) -> list[Measurement]:
async with self._lock:
return list(self._buffer)
def __len__(self) -> int:
return len(self._buffer)
12345678910111213141516171819202122232425262728293031323334353637from functools import lru_cache
from zoneinfo import ZoneInfo
from dotenv import load_dotenv
from pydantic import AnyHttpUrl
from pydantic_settings import BaseSettings, SettingsConfigDict
load_dotenv()
class Settings(BaseSettings):
source_url: AnyHttpUrl = (
"https://www.stadt-koeln.de/interne-dienste/hochwasser/pegel_ws.php"
)
refresh_seconds: int = 120
tz: str = "Europe/Berlin"
port: int = 8000
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
extra="ignore",
env_prefix="",
case_sensitive=False,
)
@property
def timezone(self) -> ZoneInfo:
try:
return ZoneInfo(self.tz)
except Exception:
return ZoneInfo("Europe/Berlin")
@lru_cache
def get_settings() -> Settings:
return Settings()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283from __future__ import annotations
import asyncio
import logging
import random
import time
from dataclasses import dataclass
from datetime import datetime
from typing import Any
import httpx
from dateutil import parser as date_parser
from defusedxml import ElementTree as ET
from .config import Settings
from .models import Measurement, resolve_trend
logger = logging.getLogger(__name__)
MAX_ATTEMPTS = 4
BASE_BACKOFF = 0.5
TIMEOUT_SECONDS = 8.0
LEVEL_KEYS = ("level", "levelcm", "pegel", "wasserstand", "value", "stand")
TIME_KEYS = (
"timestamp",
"zeit",
"time",
"datetime",
"datum",
"messzeit",
"uhrzeit",
)
TREND_KEYS = ("trend", "tendency", "richtung")
@dataclass(slots=True)
class FetchResult:
measurement: Measurement
latency_ms: float | None
is_demo: bool
error: str | None = None
class FetchError(Exception):
"""Raised when fetching from the remote source fails."""
async def fetch_latest(
settings: Settings,
previous: Measurement | None,
*,
force_demo: bool = False,
) -> FetchResult:
if force_demo:
measurement = _generate_demo(previous, settings)
return FetchResult(measurement=measurement, latency_ms=None, is_demo=True)
try:
measurement, latency = await _fetch_from_source(settings, previous)
return FetchResult(measurement=measurement, latency_ms=latency, is_demo=False)
except Exception as exc: # noqa: BLE001
logger.warning("Falling back to demo mode due to: %s", exc)
measurement = _generate_demo(previous, settings)
return FetchResult(
measurement=measurement,
latency_ms=None,
is_demo=True,
error=str(exc),
)
async def _fetch_from_source(
settings: Settings,
previous: Measurement | None,
) -> tuple[Measurement, float]:
url = str(settings.source_url)
timeout = httpx.Timeout(TIMEOUT_SECONDS)
async with httpx.AsyncClient(timeout=timeout) as client:
last_error: Exception | None = None
for attempt in range(1, MAX_ATTEMPTS + 1):
start = time.perf_counter()
try:
response = await client.get(url)
elapsed_ms = (time.perf_counter() - start) * 1000
response.raise_for_status()
measurement = _parse_response(response, settings, previous)
return measurement, elapsed_ms
except Exception as exc: # noqa: BLE001
last_error = exc
delay = BASE_BACKOFF * 2 ** (attempt - 1)
logger.debug(
"Fetch attempt %s failed (%s); retrying in %.2fs",
attempt,
exc,
delay,
)
if attempt == MAX_ATTEMPTS:
break
await asyncio.sleep(delay)
raise FetchError(f"Failed to fetch data from {url}") from last_error
def _parse_response(
response: httpx.Response,
settings: Settings,
previous: Measurement | None,
) -> Measurement:
content_type = response.headers.get("content-type", "").lower()
if "json" in content_type:
payload = response.json()
return _build_measurement_from_payload(payload, settings, previous)
text = response.text
# Try JSON first regardless of header to be robust
try:
payload = response.json()
return _build_measurement_from_payload(payload, settings, previous)
except Exception: # noqa: BLE001
pass
return _build_measurement_from_xml(text, settings, previous)
def _build_measurement_from_payload(
payload: Any,
settings: Settings,
previous: Measurement | None,
) -> Measurement:
record = _select_record(payload)
if record is None:
raise ValueError("No valid record found in payload")
normalized = {str(k).lower(): v for k, v in record.items()}
level_cm = _extract_level(normalized)
timestamp = _extract_timestamp(normalized, settings)
provided_trend = _extract_trend(normalized)
trend = resolve_trend(level_cm, provided_trend, previous)
return Measurement(level_cm=level_cm, timestamp=timestamp, trend=trend)
def _build_measurement_from_xml(
text: str,
settings: Settings,
previous: Measurement | None,
) -> Measurement:
root = ET.fromstring(text)
flat: dict[str, Any] = {}
for element in root.iter():
if element.text and element.text.strip():
flat[element.tag.lower()] = element.text.strip()
for key, value in element.attrib.items():
flat[f"{element.tag.lower()}_{key.lower()}"] = value
if not flat:
raise ValueError("XML payload did not contain any usable data")
level_cm = _extract_level(flat)
timestamp = _extract_timestamp(flat, settings)
provided_trend = _extract_trend(flat)
trend = resolve_trend(level_cm, provided_trend, previous)
return Measurement(level_cm=level_cm, timestamp=timestamp, trend=trend)
def _select_record(payload: Any) -> dict[str, Any] | None:
if isinstance(payload, dict):
if any(isinstance(v, (dict, list)) for v in payload.values()):
for key in ("latest", "current", "data", "value", "measurement", "item", "werte"):
if key in payload:
nested = _select_record(payload[key])
if nested:
return nested
return payload
if isinstance(payload, list):
for item in reversed(payload):
nested = _select_record(item)
if nested:
return nested
return None
def _extract_level(data: dict[str, Any]) -> int:
for key in LEVEL_KEYS:
if key in data:
value = data[key]
numeric = _coerce_float(value)
if numeric is not None:
# Values below 20 are likely metres; convert to centimetres.
if numeric < 20:
numeric *= 100
return max(0, int(round(numeric)))
raise ValueError("Could not determine level value")
def _extract_timestamp(data: dict[str, Any], settings: Settings) -> datetime:
tz = settings.timezone
# Handle separate date/time fields (e.g. Datum + Uhrzeit)
date_value = data.get("datum") or data.get("date")
time_value = (
data.get("uhrzeit")
or data.get("zeit")
or data.get("time")
or data.get("messzeit")
)
if date_value and time_value:
combined = f"{date_value} {time_value}"
parsed = _coerce_datetime(combined, tz)
if parsed is not None:
return parsed
for key in TIME_KEYS:
if key in data and data[key] is not None:
value = data[key]
parsed = _coerce_datetime(value, tz)
if parsed is not None:
return parsed
return datetime.now(tz)
def _extract_trend(data: dict[str, Any]) -> int | None:
for key in TREND_KEYS:
if key in data:
raw = data[key]
if raw is None:
continue
if isinstance(raw, (int, float)) and raw in (-1, 0, 1):
return int(raw)
text = str(raw).strip().lower()
if text in {"-1", "falling", "down", "sinkend"}:
return -1
if text in {"1", "rising", "up", "steigend"}:
return 1
if text in {"0", "stable", "gleich", "steady"}:
return 0
return None
def _coerce_float(value: Any) -> float | None:
if value is None:
return None
if isinstance(value, (int, float)):
return float(value)
text = str(value).strip().replace(",", ".")
try:
return float(text)
except ValueError:
return None
def _coerce_datetime(value: Any, tz) -> datetime | None:
if value is None:
return None
if isinstance(value, (int, float)):
# Assume Unix timestamp (seconds)
return datetime.fromtimestamp(float(value), tz=tz)
text = str(value).strip()
if not text:
return None
try:
parsed = date_parser.parse(text)
except (ValueError, TypeError) as exc:
logger.debug("Failed to parse datetime %s: %s", value, exc)
return None
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=tz)
return parsed.astimezone(tz)
def _generate_demo(previous: Measurement | None, settings: Settings) -> Measurement:
base = previous.level_cm if previous else 380
jitter = random.randint(-10, 10)
drift = random.choice([-3, -2, -1, 0, 1, 2, 3])
level = max(250, min(900, base + drift + jitter))
timestamp = datetime.now(settings.timezone)
trend = resolve_trend(level, None, previous)
return Measurement(level_cm=level, timestamp=timestamp, trend=trend, is_demo=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239from __future__ import annotations
import asyncio
import logging
from contextlib import asynccontextmanager, suppress
from datetime import datetime
from pathlib import Path
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, Query, Request
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from prometheus_client import CONTENT_TYPE_LATEST, generate_latest
from .cache import MeasurementCache
from .config import Settings, get_settings
from .fetcher import FetchResult, fetch_latest
from .metrics import record_fetch, set_background_state, set_data_age
from .models import HistoryResponse, LatestResponse, Measurement
logger = logging.getLogger(__name__)
BASE_DIR = Path(__file__).resolve().parent
TEMPLATES = Jinja2Templates(directory=str(BASE_DIR / "templates"))
@asynccontextmanager
async def lifespan(app: FastAPI):
logging.basicConfig(level=logging.INFO)
await service.start()
try:
yield
finally:
await service.stop()
app = FastAPI(title="Rheinpegel App", version="0.1.0", lifespan=lifespan)
app.mount("/static", StaticFiles(directory=str(BASE_DIR / "static")), name="static")
class PegelService:
def __init__(self, settings: Settings, cache: MeasurementCache) -> None:
self.settings = settings
self.cache = cache
self._lock = asyncio.Lock()
self._task: asyncio.Task[None] | None = None
async def start(self) -> None:
if self._task and not self._task.done():
return
if len(self.cache) == 0:
try:
await self.fetch_and_update()
except Exception as exc: # noqa: BLE001
logger.warning("Initial fetch failed, cache remains empty: %s", exc)
self._task = asyncio.create_task(self._run_loop())
async def stop(self) -> None:
if self._task:
self._task.cancel()
with suppress(asyncio.CancelledError):
await self._task
self._task = None
set_background_state(False)
def is_running(self) -> bool:
return self._task is not None and not self._task.done()
async def fetch_and_update(
self,
*,
force_demo: bool = False,
) -> FetchResult:
async with self._lock:
previous = await self.cache.get_latest()
result = await fetch_latest(self.settings, previous, force_demo=force_demo)
await self.cache.add(result.measurement)
self._update_metrics(result)
return result
async def latest(self) -> Measurement | None:
return await self.cache.get_latest()
async def history(self) -> list[Measurement]:
return await self.cache.get_history()
async def _run_loop(self) -> None:
set_background_state(True)
try:
while True:
try:
await self.fetch_and_update()
except Exception as exc: # noqa: BLE001
logger.exception("Background fetch failure: %s", exc)
await asyncio.sleep(self.settings.refresh_seconds)
except asyncio.CancelledError:
raise
finally:
set_background_state(False)
def _update_metrics(self, result: FetchResult) -> None:
outcome = "success"
if result.error:
outcome = "error"
elif result.is_demo:
outcome = "demo"
record_fetch(result.latency_ms, outcome)
if result.measurement:
now = datetime.now(self.settings.timezone)
age = max(0.0, (now - result.measurement.timestamp).total_seconds())
set_data_age(age)
else:
set_data_age(None)
settings = get_settings()
cache = MeasurementCache()
service = PegelService(settings=settings, cache=cache)
async def get_service() -> PegelService:
return service
def _warning_levels() -> list[dict[str, str | int]]:
return [
{"label": "Normal", "range": "< 400 cm", "color": "badge-normal", "min": 0, "max": 399},
{"label": "Aufmerksamkeit", "range": "400 – 599 cm", "color": "badge-attention", "min": 400, "max": 599},
{"label": "Warnung", "range": "600 – 799 cm", "color": "badge-warning", "min": 600, "max": 799},
{"label": "Alarm", "range": "≥ 800 cm", "color": "badge-alarm", "min": 800, "max": 9999},
]
def _sparkline_path(measurements: list[Measurement]) -> str:
if not measurements:
return ""
levels = [m.level_cm for m in measurements]
min_level = min(levels)
max_level = max(levels)
span = max(max_level - min_level, 1)
step = 100 / max(len(levels) - 1, 1)
points = []
for idx, level in enumerate(levels):
x = idx * step
y = 40 - ((level - min_level) / span * 40)
points.append(f"{x:.2f},{y:.2f}")
return "M " + " L ".join(points)
@app.get("/", response_class=HTMLResponse)
async def dashboard(
request: Request,
demo: Annotated[bool, Query(alias="demo")] = False,
service: PegelService = Depends(get_service),
) -> HTMLResponse:
if demo:
await service.fetch_and_update(force_demo=True)
latest = await service.latest()
if latest is None:
result = await service.fetch_and_update(force_demo=demo)
latest = result.measurement
history = await service.history()
sparkline = history[-24:]
sparkline_path = _sparkline_path(sparkline)
initial_payload = {
"latest": latest.model_dump(mode="json") if latest else None,
"history": [item.model_dump(mode="json") for item in history],
"autoRefresh": settings.refresh_seconds,
"demo": demo or (latest.is_demo if latest else False),
}
context = {
"request": request,
"latest": latest,
"history": history,
"sparkline": sparkline,
"sparkline_path": sparkline_path,
"auto_refresh_seconds": settings.refresh_seconds,
"timezone": settings.tz,
"warning_levels": _warning_levels(),
"demo_mode": demo or (latest.is_demo if latest else False),
"initial_payload": initial_payload,
}
return TEMPLATES.TemplateResponse("index.html.j2", context)
@app.get("/api/latest")
async def api_latest(
demo: Annotated[bool, Query(alias="demo")] = False,
service: PegelService = Depends(get_service),
) -> JSONResponse:
result = await service.fetch_and_update(force_demo=demo)
history = await service.history()
response = LatestResponse(
measurement=result.measurement,
history=history,
latency_ms=result.latency_ms,
error=result.error,
demo_mode=result.is_demo,
)
return JSONResponse(response.model_dump(mode="json"))
@app.get("/api/history")
async def api_history(service: PegelService = Depends(get_service)) -> JSONResponse:
history = await service.history()
response = HistoryResponse(data=history, demo_mode=any(item.is_demo for item in history))
return JSONResponse(response.model_dump(mode="json"))
@app.get("/healthz")
async def healthz(service: PegelService = Depends(get_service)) -> PlainTextResponse:
if not service.is_running():
raise HTTPException(status_code=503, detail="Background task not running")
return PlainTextResponse("ok")
@app.get("/metrics")
async def metrics_endpoint(service: PegelService = Depends(get_service)) -> PlainTextResponse:
latest = await service.latest()
if latest is None:
set_data_age(None)
else:
age = max(0.0, (datetime.now(settings.timezone) - latest.timestamp).total_seconds())
set_data_age(age)
data = generate_latest()
return PlainTextResponse(content=data.decode("utf-8"), media_type=CONTENT_TYPE_LATEST)
if __name__ == "__main__":
import uvicorn
uvicorn.run("app.main:app", host="0.0.0.0", port=settings.port, reload=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344from __future__ import annotations
from prometheus_client import Counter, Gauge, Histogram
FETCH_LATENCY_HIST = Histogram(
"rheinpegel_fetch_latency_seconds",
"Latency for Rheinpegel upstream fetch operations",
)
FETCH_LAST_LATENCY = Gauge(
"rheinpegel_fetch_last_latency_seconds",
"Most recent upstream fetch latency in seconds",
)
FETCH_OUTCOME_COUNTER = Counter(
"rheinpegel_fetch_total",
"Count of Rheinpegel upstream fetch attempts by outcome",
labelnames=("outcome",),
)
DATA_AGE_GAUGE = Gauge(
"rheinpegel_data_age_seconds",
"Age of the latest Rheinpegel measurement in seconds",
)
BACKGROUND_LOOP_GAUGE = Gauge(
"rheinpegel_background_loop_running",
"Indicates whether the background polling task is running",
)
def record_fetch(latency_ms: float | None, outcome: str) -> None:
if latency_ms is not None:
latency_seconds = latency_ms / 1000.0
FETCH_LATENCY_HIST.observe(latency_seconds)
FETCH_LAST_LATENCY.set(latency_seconds)
FETCH_OUTCOME_COUNTER.labels(outcome=outcome).inc()
def set_data_age(age_seconds: float | None) -> None:
if age_seconds is None:
DATA_AGE_GAUGE.set(float("nan"))
else:
DATA_AGE_GAUGE.set(max(0.0, age_seconds))
def set_background_state(running: bool) -> None:
BACKGROUND_LOOP_GAUGE.set(1.0 if running else 0.0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105from __future__ import annotations
from datetime import datetime
from enum import Enum, IntEnum
from typing import Final
from pydantic import BaseModel, ConfigDict, Field
class Trend(IntEnum):
FALLING = -1
STABLE = 0
RISING = 1
@property
def symbol(self) -> str:
return {self.FALLING: "↓", self.STABLE: "→", self.RISING: "↑"}[self]
@property
def color(self) -> str:
return {self.FALLING: "badge-falling", self.STABLE: "badge-stable", self.RISING: "badge-rising"}[self]
class WarningLevel(str, Enum):
NORMAL = "normal"
ATTENTION = "attention"
WARNING = "warning"
ALARM = "alarm"
@property
def label(self) -> str:
return {
self.NORMAL: "Normal",
self.ATTENTION: "Aufmerksamkeit",
self.WARNING: "Warnung",
self.ALARM: "Alarm",
}[self]
@property
def color(self) -> str:
return {
self.NORMAL: "badge-normal",
self.ATTENTION: "badge-attention",
self.WARNING: "badge-warning",
self.ALARM: "badge-alarm",
}[self]
WARN_THRESHOLDS: Final[tuple[tuple[int, WarningLevel], ...]] = (
(400, WarningLevel.NORMAL),
(600, WarningLevel.ATTENTION),
(800, WarningLevel.WARNING),
)
def determine_warning(level_cm: int) -> WarningLevel:
for threshold, level in WARN_THRESHOLDS:
if level_cm < threshold:
return level
return WarningLevel.ALARM
class Measurement(BaseModel):
model_config = ConfigDict(frozen=True)
level_cm: int = Field(ge=0, description="Water level in centimeters")
timestamp: datetime = Field(description="Timestamp of the measurement with tz info")
trend: Trend = Field(description="Trend indicator: -1 falling, 0 stable, 1 rising")
is_demo: bool = False
@property
def warning(self) -> WarningLevel:
return determine_warning(self.level_cm)
class HistoryResponse(BaseModel):
data: list[Measurement]
demo_mode: bool = False
class LatestResponse(BaseModel):
measurement: Measurement
history: list[Measurement] = Field(default_factory=list)
latency_ms: float | None = None
error: str | None = None
demo_mode: bool = False
def resolve_trend(
current_level: int,
provided_trend: int | None,
previous: Measurement | None,
) -> Trend:
if provided_trend in (-1, 0, 1):
return Trend(provided_trend)
if previous is None:
return Trend.STABLE
delta = current_level - previous.level_cm
if delta > 2:
return Trend.RISING
if delta < -2:
return Trend.FALLING
return Trend.STABLE
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256(() => {
const script = document.currentScript;
if (!script) {
return;
}
const apiLatest = script.dataset.apiLatest;
const refreshSeconds = Number.parseInt(script.dataset.refresh ?? "120", 10) || 120;
const demoFlag = script.dataset.demo === "true";
const timezone = document.body?.dataset?.timezone || "Europe/Berlin";
const levelValue = document.getElementById("levelValue");
const warningBadge = document.getElementById("warningBadge");
const trendBadge = document.getElementById("trendBadge");
const trendSymbol = document.getElementById("trendSymbol");
const updatedTime = document.getElementById("updatedTime");
const relativeAge = document.getElementById("relativeAge");
const countdown = document.getElementById("countdown");
const refreshButton = document.getElementById("refreshButton");
const autoToggle = document.getElementById("autoRefreshToggle");
const sparklinePath = document.getElementById("sparklinePath");
const errorBanner = document.getElementById("errorBanner");
const demoBadge = document.getElementById("demoBadge");
const initialDataEl = document.getElementById("initial-data");
let initialPayload = { latest: null, history: [], autoRefresh: refreshSeconds, demo: demoFlag };
if (initialDataEl?.textContent) {
try {
initialPayload = JSON.parse(initialDataEl.textContent);
} catch (err) {
console.warn("Failed to parse initial payload", err);
}
}
const state = {
autoRefresh: true,
secondsRemaining: refreshSeconds,
lastMeasurement: initialPayload.latest ?? null,
history: initialPayload.history ?? [],
demoMode: demoFlag || Boolean(initialPayload.demo),
timezone,
};
const dateFormatter = new Intl.DateTimeFormat("de-DE", {
timeZone: timezone,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
function showError(message) {
if (!errorBanner) return;
errorBanner.textContent = message;
errorBanner.hidden = false;
}
function clearError() {
if (!errorBanner) return;
errorBanner.textContent = "";
errorBanner.hidden = true;
}
function warningFor(level) {
if (level < 400) {
return { label: "Normal", cls: "badge-normal" };
}
if (level < 600) {
return { label: "Aufmerksamkeit", cls: "badge-attention" };
}
if (level < 800) {
return { label: "Warnung", cls: "badge-warning" };
}
return { label: "Alarm", cls: "badge-alarm" };
}
function trendInfo(trendValue) {
switch (trendValue) {
case 1:
return { label: "steigend", symbol: "↑", cls: "badge-rising" };
case -1:
return { label: "fallend", symbol: "↓", cls: "badge-falling" };
default:
return { label: "gleichbleibend", symbol: "→", cls: "badge-stable" };
}
}
function computeSparkline(history) {
if (!history || history.length === 0) {
return "";
}
const levels = history.map((entry) => Number(entry.level_cm ?? entry.levelCm)).filter((v) => Number.isFinite(v));
if (levels.length === 0) {
return "";
}
const min = Math.min(...levels);
const max = Math.max(...levels);
const span = Math.max(max - min, 1);
const step = 100 / Math.max(levels.length - 1, 1);
const parts = levels.map((level, index) => {
const x = index * step;
const y = 40 - ((level - min) / span) * 40;
return `${x.toFixed(2)},${y.toFixed(2)}`;
});
return `M ${parts.join(" L ")}`;
}
function updateDemoBadge(isDemo) {
if (!demoBadge) return;
if (isDemo) {
demoBadge.hidden = false;
document.body?.setAttribute("data-demo", "true");
} else {
demoBadge.hidden = true;
document.body?.setAttribute("data-demo", "false");
}
}
function updateUI(measurement, history) {
if (!measurement) {
showError("Keine Messdaten verfügbar");
return;
}
state.lastMeasurement = measurement;
state.history = history ?? state.history;
clearError();
if (levelValue) {
levelValue.textContent = measurement.level_cm ?? measurement.levelCm;
}
const warning = warningFor(measurement.level_cm ?? measurement.levelCm);
if (warningBadge) {
warningBadge.className = `badge ${warning.cls}`;
warningBadge.textContent = warning.label;
}
const trend = trendInfo(measurement.trend);
if (trendBadge) {
trendBadge.className = `badge trend-badge ${trend.cls}`;
trendBadge.setAttribute("aria-label", `Trend ${trend.label}`);
}
if (trendSymbol) {
trendSymbol.textContent = trend.symbol;
}
if (updatedTime) {
updatedTime.dataset.timestamp = measurement.timestamp;
const date = new Date(measurement.timestamp);
updatedTime.textContent = `Zuletzt aktualisiert: ${dateFormatter.format(date)} Uhr`;
}
updateRelativeAge();
updateDemoBadge(Boolean(measurement.is_demo ?? measurement.isDemo));
if (sparklinePath) {
sparklinePath.setAttribute("d", computeSparkline(state.history.slice(-24)));
}
}
function updateRelativeAge() {
if (!relativeAge || !state.lastMeasurement?.timestamp) {
return;
}
const lastDate = new Date(state.lastMeasurement.timestamp);
const diffSeconds = Math.max(0, Math.floor((Date.now() - lastDate.getTime()) / 1000));
if (diffSeconds < 5) {
relativeAge.textContent = "vor wenigen Sekunden";
return;
}
if (diffSeconds < 60) {
relativeAge.textContent = `vor ${diffSeconds} Sekunden`;
return;
}
const minutes = Math.floor(diffSeconds / 60);
const seconds = diffSeconds % 60;
relativeAge.textContent = `vor ${minutes} Minute${minutes === 1 ? "" : "n"} und ${seconds} Sekunde${seconds === 1 ? "" : "n"}`;
}
function updateCountdown() {
if (!countdown) return;
if (!state.autoRefresh) {
countdown.textContent = "Auto-Refresh deaktiviert";
return;
}
const minutes = Math.floor(state.secondsRemaining / 60);
const seconds = state.secondsRemaining % 60;
countdown.textContent = `Nächste Aktualisierung in ${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
}
async function refreshNow() {
if (!apiLatest) return;
if (refreshButton) {
refreshButton.disabled = true;
}
try {
const url = new URL(apiLatest, window.location.origin);
if (state.demoMode) {
url.searchParams.set("demo", "1");
}
const response = await fetch(url.toString(), { headers: { Accept: "application/json" } });
if (!response.ok) {
throw new Error(`Serverfehler ${response.status}`);
}
const payload = await response.json();
if (payload.error) {
showError(payload.error);
} else {
clearError();
}
state.demoMode = Boolean(payload.demo_mode ?? payload.demoMode ?? state.demoMode);
updateUI(payload.measurement, payload.history);
state.secondsRemaining = refreshSeconds;
updateCountdown();
} catch (error) {
console.error("Aktualisierung fehlgeschlagen", error);
showError("Aktualisierung fehlgeschlagen. Bitte später erneut versuchen.");
} finally {
if (refreshButton) {
refreshButton.disabled = false;
}
}
}
if (autoToggle) {
autoToggle.addEventListener("change", (event) => {
state.autoRefresh = event.target.checked;
autoToggle.setAttribute("aria-checked", state.autoRefresh ? "true" : "false");
if (state.autoRefresh) {
state.secondsRemaining = refreshSeconds;
}
updateCountdown();
});
}
if (refreshButton) {
refreshButton.addEventListener("click", () => {
refreshNow();
});
}
setInterval(() => {
if (!state.autoRefresh) {
return;
}
state.secondsRemaining -= 1;
if (state.secondsRemaining <= 0) {
state.secondsRemaining = refreshSeconds;
refreshNow();
}
updateCountdown();
}, 1000);
setInterval(updateRelativeAge, 1000);
updateUI(state.lastMeasurement, state.history);
updateCountdown();
})();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331:root {
color-scheme: light dark;
--bg-color: #f8fafc;
--text-color: #0f172a;
--card-bg: #ffffff;
--border-color: #e2e8f0;
--accent: #2563eb;
--accent-hover: #1d4ed8;
--badge-normal: #15803d;
--badge-attention: #f97316;
--badge-warning: #ea580c;
--badge-alarm: #dc2626;
--badge-stable: #64748b;
--badge-rising: #16a34a;
--badge-falling: #0ea5e9;
--badge-demo: #7c3aed;
--muted: #94a3b8;
--font-sans: "Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-color: #0f172a;
--text-color: #e2e8f0;
--card-bg: #1e293b;
--border-color: #334155;
--accent: #3b82f6;
--accent-hover: #2563eb;
}
}
* {
box-sizing: border-box;
}
body.page {
margin: 0;
padding: 0 1.5rem;
font-family: var(--font-sans);
background: var(--bg-color);
color: var(--text-color);
min-height: 100vh;
display: flex;
flex-direction: column;
gap: 2rem;
}
.site-header {
padding-top: 2rem;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 1rem;
}
.title-block h1 {
font-size: clamp(2rem, 4vw, 2.75rem);
margin: 0;
}
.subtitle {
margin: 0;
font-size: 1rem;
color: var(--muted);
}
.layout {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
width: min(1100px, 100%);
margin: 0 auto;
}
.card {
background: var(--card-bg);
border: 1px solid var(--border-color);
border-radius: 18px;
padding: 1.5rem;
box-shadow: 0 18px 36px rgba(15, 23, 42, 0.08);
}
.alert {
margin-bottom: 1rem;
padding: 0.75rem 1rem;
border-radius: 12px;
background: rgba(220, 38, 38, 0.12);
color: #dc2626;
font-weight: 600;
}
.alert[hidden] {
display: none;
}
.card-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
}
.card-header h2 {
margin: 0;
font-size: 1.35rem;
}
.level-display {
display: flex;
align-items: center;
gap: 1rem;
margin: 1.5rem 0;
}
.level-number {
font-size: clamp(3rem, 6vw, 4.5rem);
font-weight: 700;
line-height: 1;
}
.level-number .unit {
font-size: 1rem;
margin-left: 0.25rem;
color: var(--muted);
}
.badge {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.35rem 0.75rem;
border-radius: 999px;
font-size: 0.85rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
background: var(--border-color);
color: var(--text-color);
}
.badge-normal { background: rgba(21, 128, 61, 0.15); color: #15803d; }
.badge-attention { background: rgba(249, 115, 22, 0.18); color: #f97316; }
.badge-warning { background: rgba(234, 88, 12, 0.18); color: #ea580c; }
.badge-alarm { background: rgba(220, 38, 38, 0.18); color: #dc2626; }
.badge-stable { background: rgba(100, 116, 139, 0.18); color: #475569; }
.badge-rising { background: rgba(22, 163, 74, 0.18); color: #16a34a; }
.badge-falling { background: rgba(14, 165, 233, 0.18); color: #0284c7; }
.badge-demo { background: rgba(124, 58, 237, 0.18); color: #7c3aed; }
.badge-muted { background: rgba(148, 163, 184, 0.2); color: #475569; }
.trend-badge {
font-size: 1.25rem;
min-width: 3rem;
justify-content: center;
}
.status-meta {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
color: var(--muted);
font-size: 0.95rem;
}
.controls {
display: flex;
align-items: center;
gap: 1rem;
flex-wrap: wrap;
margin: 1.5rem 0 1rem;
}
.btn {
border: none;
border-radius: 999px;
padding: 0.65rem 1.5rem;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: background 0.2s ease, transform 0.1s ease;
}
.btn.primary {
background: var(--accent);
color: #fff;
}
.btn.primary:focus-visible,
.btn.primary:hover {
background: var(--accent-hover);
transform: translateY(-1px);
outline: 2px solid transparent;
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.3);
}
.toggle {
display: inline-flex;
align-items: center;
gap: 0.5rem;
font-weight: 500;
}
.toggle input {
width: 2.5rem;
height: 1.4rem;
appearance: none;
background: var(--border-color);
border-radius: 999px;
position: relative;
cursor: pointer;
transition: background 0.2s ease;
}
.toggle input::after {
content: "";
position: absolute;
top: 0.2rem;
left: 0.25rem;
width: 1rem;
height: 1rem;
border-radius: 50%;
background: #fff;
transition: transform 0.2s ease;
}
.toggle input:checked {
background: var(--accent);
}
.toggle input:checked::after {
transform: translateX(1.05rem);
}
.toggle input:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.sparkline {
margin: 0;
}
.sparkline svg {
width: 100%;
height: 120px;
}
.sparkline path {
fill: none;
stroke: var(--accent);
stroke-width: 2;
stroke-linejoin: round;
stroke-linecap: round;
}
.sparkline .baseline {
stroke: rgba(148, 163, 184, 0.3);
stroke-width: 1;
}
.legend-card {
display: flex;
flex-direction: column;
gap: 1rem;
}
.legend-list {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.legend-item {
display: flex;
align-items: center;
gap: 0.75rem;
}
.legend-label {
font-weight: 600;
}
.legend-range {
color: var(--muted);
font-size: 0.9rem;
}
.hint {
margin: 0;
font-size: 0.85rem;
color: var(--muted);
}
.site-footer {
margin-top: auto;
padding-bottom: 2rem;
text-align: center;
color: var(--muted);
font-size: 0.85rem;
}
button:focus-visible,
input:focus-visible,
a:focus-visible {
outline: 3px solid rgba(37, 99, 235, 0.5);
outline-offset: 2px;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
@media (max-width: 640px) {
body.page {
padding: 0 1rem;
}
.controls {
justify-content: space-between;
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Rheinpegel Köln</title>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link rel="stylesheet" href="{{ url_for('static', path='styles.css') }}" />
<script
defer
src="{{ url_for('static', path='app.js') }}"
data-api-latest="{{ url_for('api_latest') }}"
data-api-history="{{ url_for('api_history') }}"
data-refresh="{{ auto_refresh_seconds }}"
data-demo="{{ 'true' if demo_mode else 'false' }}"
></script>
</head>
<body class="page" data-demo="{{ 'true' if demo_mode else 'false' }}" data-timezone="{{ timezone }}">
<header class="site-header">
<div class="title-block">
<h1>Rheinpegel Köln</h1>
<p class="subtitle">Aktueller Wasserstand, Trend und Verlauf der letzten 48 Messpunkte</p>
</div>
<span id="demoBadge" class="badge badge-demo" {% if not demo_mode %}hidden{% endif %} aria-live="polite">Demo-Modus aktiv</span>
</header>
<main class="layout">
<section class="card status-card" aria-labelledby="status-heading">
<header class="card-header">
<h2 id="status-heading">Aktueller Pegel</h2>
{% if latest %}
<span id="warningBadge" class="badge {{ latest.warning.color }}">{{ latest.warning.label }}</span>
{% else %}
<span id="warningBadge" class="badge badge-muted">Keine Daten</span>
{% endif %}
</header>
<div id="errorBanner" class="alert" role="alert" hidden aria-live="assertive"></div>
<div class="level-display">
<span class="level-number" aria-live="polite">
<span id="levelValue" class="level-number-value">{% if latest %}{{ latest.level_cm }}{% else %}–{% endif %}</span>
<span class="unit">cm</span>
</span>
{% set trend_class = 'badge-stable' %}
{% set trend_label = 'gleichbleibend' %}
{% set trend_symbol = '→' %}
{% if latest %}
{% if latest.trend.value == 1 %}
{% set trend_class = 'badge-rising' %}
{% set trend_label = 'steigend' %}
{% set trend_symbol = '↑' %}
{% elif latest.trend.value == -1 %}
{% set trend_class = 'badge-falling' %}
{% set trend_label = 'fallend' %}
{% set trend_symbol = '↓' %}
{% endif %}
{% endif %}
<span id="trendBadge" class="badge trend-badge {{ trend_class }}" aria-live="polite" aria-label="Trend {{ trend_label }}">
<span id="trendSymbol">{{ trend_symbol }}</span>
<span id="trendText" class="sr-only">{{ trend_label }}</span>
</span>
</div>
<div class="status-meta" aria-live="polite">
<span id="updatedTime" data-timestamp="{% if latest %}{{ latest.timestamp.isoformat() }}{% endif %}">
{% if latest %}
Zuletzt aktualisiert: {{ latest.timestamp.astimezone().strftime('%d.%m.%Y %H:%M:%S') }} Uhr
{% else %}
Keine Messwerte verfügbar
{% endif %}
</span>
<span id="relativeAge">{% if latest %}vor wenigen Sekunden{% endif %}</span>
</div>
<div class="controls" role="group" aria-label="Datenaktualisierung">
<button type="button" id="refreshButton" class="btn primary">Jetzt aktualisieren</button>
<label class="toggle" for="autoRefreshToggle">
<input type="checkbox" id="autoRefreshToggle" checked aria-checked="true" />
<span>Auto-Refresh</span>
</label>
<span id="countdown" aria-live="polite">Nächste Aktualisierung in {{ '%02d:%02d'|format((auto_refresh_seconds // 60), (auto_refresh_seconds % 60)) }}</span>
</div>
<figure class="sparkline" role="img" aria-label="Sparkline der letzten 24 Messwerte">
<svg id="sparklineChart" viewBox="0 0 100 40" preserveAspectRatio="none">
<path id="sparklinePath" d="{{ sparkline_path }}" />
<line class="baseline" x1="0" x2="100" y1="40" y2="40" />
</svg>
<figcaption>Verlauf der letzten 24 Messungen</figcaption>
</figure>
</section>
<section class="card legend-card" aria-labelledby="legend-heading">
<h2 id="legend-heading">Warnstufen</h2>
<ul class="legend-list">
{% for level in warning_levels %}
<li class="legend-item">
<span class="badge {{ level.color }}" aria-hidden="true"></span>
<span class="legend-label">{{ level.label }}</span>
<span class="legend-range">{{ level.range }}</span>
</li>
{% endfor %}
</ul>
<p class="hint">Trend an/aus beeinflusst nur die Anzeige im Browser. Serverseitige Aktualisierung läuft unabhängig.</p>
</section>
</main>
<footer class="site-footer">
<small>Quelle: Stadt Köln – aktualisiert alle {{ auto_refresh_seconds }} Sekunden. Zeitzone: {{ timezone }}.</small>
</footer>
<script type="application/json" id="initial-data">{{ initial_payload | tojson }}</script>
</body>
</html>1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290[
{
"level_cm": 368,
"timestamp": "2025-10-27T17:20:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T17:25:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T17:30:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T17:35:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T17:40:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T17:45:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T17:50:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T17:55:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T18:00:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T18:05:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T18:10:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T18:15:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T18:20:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T18:25:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T18:30:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T18:35:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T18:40:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T18:45:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 369,
"timestamp": "2025-10-27T18:50:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 369,
"timestamp": "2025-10-27T18:55:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 369,
"timestamp": "2025-10-27T19:00:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T19:05:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T19:10:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T19:15:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T19:20:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T19:25:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T19:30:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T19:35:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T19:40:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T19:45:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 369,
"timestamp": "2025-10-27T19:50:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 369,
"timestamp": "2025-10-27T19:55:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 369,
"timestamp": "2025-10-27T20:00:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T20:05:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T20:10:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T20:15:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 369,
"timestamp": "2025-10-27T20:20:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 369,
"timestamp": "2025-10-27T20:25:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 369,
"timestamp": "2025-10-27T20:30:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T20:35:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T20:40:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T20:45:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 369,
"timestamp": "2025-10-27T20:50:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 369,
"timestamp": "2025-10-27T20:55:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 369,
"timestamp": "2025-10-27T21:00:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T21:05:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T21:10:00+01:00",
"trend": 0,
"is_demo": false
},
{
"level_cm": 368,
"timestamp": "2025-10-27T21:15:00+01:00",
"trend": 0,
"is_demo": false
}
]123456789101112131415version: "3.9"
services:
rheinpegel:
build: .
image: rheinpegel-app:latest
ports:
- "${PORT:-8000}:8000"
environment:
SOURCE_URL: "https://www.stadt-koeln.de/interne-dienste/hochwasser/pegel_ws.php"
REFRESH_SECONDS: "120"
TZ: "Europe/Berlin"
PORT: "8000"
volumes:
- ./data:/app/data
restart: unless-stopped123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263[build-system]
requires = ["setuptools>=65", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "rheinpegel-app"
version = "0.1.0"
description = "FastAPI app showing current Rhine water levels with caching and modern UI"
readme = "README.md"
authors = [{ name = "Rheinpegel Team" }]
license = { text = "MIT" }
requires-python = ">=3.11"
dependencies = [
"fastapi>=0.111",
"uvicorn[standard]>=0.29",
"httpx>=0.27",
"python-dotenv>=1.0",
"jinja2>=3.1",
"pydantic>=2.7",
"pydantic-settings>=2.4",
"prometheus-client>=0.20",
"python-dateutil>=2.9",
"defusedxml>=0.7"
]
[project.optional-dependencies]
dev = [
"pytest>=8.2",
"pytest-asyncio>=0.23",
"httpx>=0.27",
"ruff>=0.5.6",
"black>=24.4"
]
[tool.setuptools]
package-dir = {"" = "."}
include-package-data = true
[tool.setuptools.packages.find]
where = ["."]
include = ["app*"]
[tool.setuptools.package-data]
"app" = ["templates/*.j2", "static/*"]
[tool.black]
line-length = 88
target-version = ["py311"]
[tool.ruff]
line-length = 88
target-version = "py311"
select = ["E", "F", "B", "I", "UP", "ASYNC", "S", "N"]
ignore = ["S101"]
type-checking-mode = "basic"
[tool.ruff.lint.isort]
known-first-party = ["app"]
[tool.pytest.ini_options]
asyncio_mode = "auto"
addopts = "-q"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139Metadata-Version: 2.4
Name: rheinpegel-app
Version: 0.1.0
Summary: FastAPI app showing current Rhine water levels with caching and modern UI
Author: Rheinpegel Team
License: MIT
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: fastapi>=0.111
Requires-Dist: uvicorn[standard]>=0.29
Requires-Dist: httpx>=0.27
Requires-Dist: python-dotenv>=1.0
Requires-Dist: jinja2>=3.1
Requires-Dist: pydantic>=2.7
Requires-Dist: pydantic-settings>=2.4
Requires-Dist: prometheus-client>=0.20
Requires-Dist: python-dateutil>=2.9
Requires-Dist: defusedxml>=0.7
Provides-Extra: dev
Requires-Dist: pytest>=8.2; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: httpx>=0.27; extra == "dev"
Requires-Dist: ruff>=0.5.6; extra == "dev"
Requires-Dist: black>=24.4; extra == "dev"
# Rheinpegel App
Eine moderne FastAPI-Anwendung, die den aktuellen Rheinpegel (Köln) abruft, zwischenspeichert und visuell aufbereitet. Die Anwendung kombiniert serverseitiges Polling mit einem reaktiven Frontend (AJAX, Countdown, Sparkline) und liefert zusätzlich Status- sowie Prometheus-Kennzahlen.
## Hauptfunktionen
- **Asynchrones Polling** der offiziellen Quelle via `httpx` mit Timeout (8 s) und exponentiellem Backoff (4 Versuche).
- **Automatische Format-Erkennung** für JSON oder XML und robuste Feldzuordnung.
- **Trend-Berechnung** aus Rohdaten oder anhand der letzten Messwerte (Δ > 2 cm ⇒ ↑, Δ < −2 ⇒ ↓).
- **Mehrstufiges Caching**: In-Memory-Ringpuffer (48 Werte) + JSON-Persistenz unter `data/cache.json`.
- **Demo-Modus** bei Netzwerkfehlern oder via `?demo=1` mit synthetischen, plausiblen Messwerten.
- **FastAPI + Jinja2** Dashboard mit responsive Karte, Warnstufen, Sparkline (Inline-SVG) sowie Auto-Refresh-Toggle und Countdown.
- **Prometheus-Metriken**: letzte Latenz, Erfolgs-/Fehlerzähler, Datenalter und Health-Endpoint.
## Voraussetzungen
- Python 3.11+
- Optional: [uv](https://github.com/astral-sh/uv) für schnelle virtuelle Umgebungen
## Installation & Setup
### Variante A: uv
```bash
uv venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
uv pip install -e .
cp .env.example .env
```
### Variante B: pip / venv
```bash
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install --upgrade pip
pip install -e .
copy .env.example .env # Windows
```
> **Hinweis:** Die Umgebungsvariablen (.env) steuern u.a. den Polling-Intervall (`REFRESH_SECONDS`), die Quelle (`SOURCE_URL`) und die Zeitzone (`TZ`).
## Starten der Anwendung
```bash
uvicorn app.main:app --reload
# oder
python -m app.main
```
Die Oberfläche ist anschließend unter http://127.0.0.1:8000 erreichbar.
## Wichtige Endpunkte
| Route | Beschreibung |
|-----------------|-------------------------------------------------|
| `/` | Dashboard mit Live-Karte, Trend, Sparkline |
| `/api/latest` | Neueste Messung (JSON) + komplette Historie |
| `/api/history` | Maximal 48 Messpunkte aus dem Ringpuffer |
| `/healthz` | 200 OK, wenn der Hintergrund-Task aktiv ist |
| `/metrics` | Prometheus-kompatible Kennzahlen |
### Demo-Modus
Alle Endpunkte akzeptieren `?demo=1`, um synthetische Daten zu liefern und das UI als „Demo“ zu markieren.
## Tests
```bash
pytest
```
Die Tests decken das Parsing (JSON/XML) sowie zentrale FastAPI-Endpunkte ab.
## Docker
```bash
docker build -t rheinpegel-app .
docker run -p 8000:8000 --env-file .env rheinpegel-app
```
Oder via Compose:
```bash
docker-compose up --build
```
Der Container läuft als Non-Root-User, besitzt einen Healthcheck (`/healthz`) und bindet `./data` für persistente Caches ein.
## Beispiel systemd Unit (optional)
```ini
[Unit]
Description=Rheinpegel App
After=network.target
[Service]
User=www-data
WorkingDirectory=/opt/rheinpegel-app
EnvironmentFile=/opt/rheinpegel-app/.env
ExecStart=/opt/rheinpegel-app/.venv/bin/uvicorn app.main:app --host 0.0.0.0 --port 8000
Restart=always
[Install]
WantedBy=multi-user.target
```
## Weiterentwicklung
- UI-Optimierungen, z. B. zusätzliche Karten oder historische Auswertungen
- Export in weitere Formate (CSV/ICS)
- Alarm-Benachrichtigungen (E-Mail, Webhooks) basierend auf Warnstufen
Viel Spaß beim Ausprobieren der Rheinpegel-App!12345678910111213141516171819README.md
pyproject.toml
./app/__init__.py
./app/cache.py
./app/config.py
./app/fetcher.py
./app/main.py
./app/metrics.py
./app/models.py
./app/static/app.js
./app/static/styles.css
./app/templates/index.html.j2
rheinpegel_app.egg-info/PKG-INFO
rheinpegel_app.egg-info/SOURCES.txt
rheinpegel_app.egg-info/dependency_links.txt
rheinpegel_app.egg-info/requires.txt
rheinpegel_app.egg-info/top_level.txt
tests/test_endpoints.py
tests/test_parser.py1
1234567891011121314151617fastapi>=0.111
uvicorn[standard]>=0.29
httpx>=0.27
python-dotenv>=1.0
jinja2>=3.1
pydantic>=2.7
pydantic-settings>=2.4
prometheus-client>=0.20
python-dateutil>=2.9
defusedxml>=0.7
[dev]
pytest>=8.2
pytest-asyncio>=0.23
httpx>=0.27
ruff>=0.5.6
black>=24.41app1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677from __future__ import annotations
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
import pytest
from httpx import ASGITransport, AsyncClient
from app import main
from app.fetcher import FetchResult
from app.models import Measurement, Trend
class FakeService:
def __init__(self) -> None:
self._tz = ZoneInfo("Europe/Berlin")
self._history: list[Measurement] = [
Measurement(level_cm=400, timestamp=datetime.now(self._tz) - timedelta(minutes=10), trend=Trend.STABLE)
]
self.refresh_seconds = 120
async def start(self) -> None: # pragma: no cover - noop for tests
return None
async def stop(self) -> None: # pragma: no cover - noop for tests
return None
def is_running(self) -> bool:
return True
async def fetch_and_update(self, *, force_demo: bool = False) -> FetchResult:
base = self._history[-1].level_cm
level = base + (3 if force_demo else 1)
measurement = Measurement(
level_cm=level,
timestamp=datetime.now(self._tz),
trend=Trend.RISING if level > base else Trend.STABLE,
is_demo=force_demo,
)
self._history.append(measurement)
return FetchResult(measurement=measurement, latency_ms=42.0, is_demo=force_demo)
async def latest(self) -> Measurement | None:
return self._history[-1]
async def history(self) -> list[Measurement]:
return list(self._history[-5:])
@pytest.fixture
async def test_client(monkeypatch) -> AsyncClient:
fake_service = FakeService()
monkeypatch.setattr(main, "service", fake_service)
main.app.dependency_overrides[main.get_service] = lambda: fake_service
transport = ASGITransport(app=main.app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
yield client
main.app.dependency_overrides.clear()
@pytest.mark.asyncio
async def test_api_latest_returns_measurement(test_client: AsyncClient) -> None:
response = await test_client.get("/api/latest")
assert response.status_code == 200
payload = response.json()
assert payload["measurement"]["level_cm"] >= 401
assert payload["history"]
assert payload["latency_ms"] == 42.0
@pytest.mark.asyncio
async def test_api_history_returns_entries(test_client: AsyncClient) -> None:
response = await test_client.get("/api/history")
assert response.status_code == 200
payload = response.json()
assert "data" in payload
assert len(payload["data"]) <= 512345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758from datetime import datetime
from zoneinfo import ZoneInfo
import pytest
from app.config import Settings
from app.fetcher import _build_measurement_from_payload, _build_measurement_from_xml
from app.models import Measurement, Trend
@pytest.fixture
def settings() -> Settings:
return Settings(
source_url="https://example.com",
refresh_seconds=120,
tz="Europe/Berlin",
port=8000,
)
def test_parse_json_payload(settings: Settings) -> None:
previous = Measurement(
level_cm=350,
timestamp=datetime(2024, 1, 1, 11, 0, tzinfo=ZoneInfo("Europe/Berlin")),
trend=Trend.STABLE,
)
payload = {
"level": 356.4,
"timestamp": "2024-01-01T10:00:00Z",
}
measurement = _build_measurement_from_payload(payload, settings, previous)
assert measurement.level_cm == 356
assert measurement.trend == Trend.RISING
assert measurement.timestamp.tzinfo is not None
assert measurement.timestamp.tzinfo.key == "Europe/Berlin"
def test_parse_xml_payload(settings: Settings) -> None:
previous = Measurement(
level_cm=410,
timestamp=datetime(2024, 1, 1, 12, 0, tzinfo=ZoneInfo("Europe/Berlin")),
trend=Trend.STABLE,
)
xml = """
<root>
<Wasserstand>404.2</Wasserstand>
<Messzeit>2024-01-01T10:00:00Z</Messzeit>
</root>
"""
measurement = _build_measurement_from_xml(xml, settings, previous)
assert measurement.level_cm == 404
assert measurement.trend == Trend.FALLING
assert measurement.timestamp.astimezone(ZoneInfo("Europe/Berlin")).hour == 11.env.exampleAdded+4
.pytest_cache/.gitignoreAdded+2
.pytest_cache/CACHEDIR.TAGAdded+4
.pytest_cache/README.mdAdded+8
.pytest_cache/v/cache/lastfailedAdded+1
.pytest_cache/v/cache/nodeidsAdded+6
DockerfileAdded+41
README.md+118-10
app/__init__.pyAdded+1
app/__pycache__/__init__.cpython-313.pycAdded
app/__pycache__/cache.cpython-313.pycAdded
app/__pycache__/config.cpython-313.pycAdded
app/__pycache__/fetcher.cpython-313.pycAdded
app/__pycache__/main.cpython-313.pycAdded
app/__pycache__/metrics.cpython-313.pycAdded
app/__pycache__/models.cpython-313.pycAdded
app/cache.pyAdded+72
app/config.pyAdded+37
app/fetcher.pyAdded+283
app/main.pyAdded+239
app/metrics.pyAdded+44
app/models.pyAdded+105
app/static/app.jsAdded+256
app/static/styles.cssAdded+331
app/templates/index.html.j2Added+106
data/.gitkeepAdded+1
data/cache.jsonAdded+290
docker-compose.ymlAdded+15
pyproject.tomlAdded+63
rheinpegel_app.egg-info/PKG-INFOAdded+139
rheinpegel_app.egg-info/SOURCES.txtAdded+19
rheinpegel_app.egg-info/dependency_links.txtAdded+1
rheinpegel_app.egg-info/requires.txtAdded+17
rheinpegel_app.egg-info/top_level.txtAdded+1
tests/__pycache__/test_endpoints.cpython-313-pytest-8.4.1.pycAdded
tests/__pycache__/test_parser.cpython-313-pytest-8.4.1.pycAdded
tests/test_endpoints.pyAdded+77
tests/test_parser.pyAdded+58