Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d0ab53185c | |||
| 3101122975 |
13
TASK.md
13
TASK.md
@ -1,8 +1,9 @@
|
||||
# TASK 4:
|
||||
# TASK 6:
|
||||
|
||||
Wir arbeiten nun intern direkt mit den Daten von Overpass. Macht das Sinn? Warum vielleicht nicht?
|
||||
* bbox für Schweiz scheint zu gross und wirft einen error ... Lösungsmöglichkeiten?
|
||||
-> Wir können die Schweiz (Koordinaten) in Unterregionen aufsplitten. Macht das bitte.
|
||||
-> entfernt dazu die bbox für 'davos', nehmt die 'schweiz' und splittet sie in 4, 9 oder 16 Koordinaten-Tuples auf.
|
||||
|
||||
* Versucht einen Adapter zu bauen, wir wollen intern mit einer eigenen Dataclass `POI` arbeiten. Wir bauen also dazu eine
|
||||
Funktion `load_pois`, welche einerseits die Daten fetched und andererseits auch parsed. Den Fetching-Teil haben wir
|
||||
bereits (`fetch_overpass`), den Pasing-Teil haben wir noch nicht.
|
||||
Schreibt bitte eine eigene Dataclass`Poi` in welche die gefetchten Daten 'abgefüllt' werden können.
|
||||
* Speichert und loggt in welchen Koordinaten-Tuples ein Fehler auftritt (gebt am Schluss eine Zusammenfassung
|
||||
dieser fehlerhaften Queries aus)
|
||||
* Bildet ein neues Modul `storage.py` und baut den Code, welcher zum Speichern der POIS als .json auf der Festplatte nötig ist.
|
||||
BIN
__pycache__/models.cpython-313.pyc
Normal file
BIN
__pycache__/models.cpython-313.pyc
Normal file
Binary file not shown.
Binary file not shown.
48
main.py
48
main.py
@ -1,4 +1,23 @@
|
||||
from overpass import fetch_overpass, OverpassApiError
|
||||
from overpass import load_pois, OverpassApiError
|
||||
from models import POI
|
||||
import logging
|
||||
from queries.bergbahn import BERGBAHN_QUERY
|
||||
from queries.restaurant import RESTAURANT_QUERY
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Logging konfigurieren
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Erinnerung: Log-Levels -> DEBUG, INFO, WARNING, ERROR, CRITICAL
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(message)s",
|
||||
datefmt="%H:%M:%S",
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Konfiguration
|
||||
@ -9,32 +28,29 @@ BBOXEN = {
|
||||
"schweiz": (45.8, 5.9, 47.8, 10.5),
|
||||
}
|
||||
|
||||
QUERY = """
|
||||
[out:json][timeout:2][maxsize:500000];
|
||||
(
|
||||
node["aerialway"="station"]({bbox});
|
||||
way["aerialway"="station"]({bbox});
|
||||
node["railway"="funicular"]({bbox});
|
||||
way["railway"="funicular"]({bbox});
|
||||
node["railway"="station"]["funicular"="yes"]({bbox});
|
||||
);
|
||||
out center body;
|
||||
"""
|
||||
QUERY = {"bergbahn": BERGBAHN_QUERY}
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Hauptlogik
|
||||
# ---------------------------------------------------------------------------
|
||||
def main() -> None:
|
||||
|
||||
query_name = list(QUERY.keys())[0]
|
||||
|
||||
for name, bbox in BBOXEN.items():
|
||||
logger.info(f"Starte Abfrage für Query: {query_name}, '{name}' mit bbox={bbox}")
|
||||
try:
|
||||
result = fetch_overpass(overpass_query=QUERY, bbox=bbox)
|
||||
pois: list[POI] = load_pois(overpass_query=QUERY.get(query_name,""), bbox=bbox)
|
||||
except OverpassApiError as exc:
|
||||
print(f" Fehler : {exc}")
|
||||
logger.error(f"Fehler bei '{name}': {exc}")
|
||||
continue
|
||||
|
||||
elements = result.get("elements", [])
|
||||
print(elements)
|
||||
logger.info(f"\n{name}: {len(pois)} POIs gefunden")
|
||||
for poi in pois:
|
||||
logger.info(f" {poi.id}: ({poi.lat}, {poi.lon})")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
15
models.py
Normal file
15
models.py
Normal file
@ -0,0 +1,15 @@
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
@dataclass
|
||||
class POI:
|
||||
id: str
|
||||
type: str
|
||||
lat: float
|
||||
lon: float
|
||||
tags: dict = field(default_factory=dict) # weil mutable defaults in Dataclasses eine bekannte Python-Falle sind
|
||||
# (alle Instanzen würden dasselbe Dict teilen...)
|
||||
|
||||
|
||||
# REMARK:
|
||||
# Wann eine eigene Dataclass für tags?
|
||||
# Nur wenn die tags strukturiert und vorhersehbar sind, was bei OSM-Daten nicht der Fall ist...
|
||||
66
overpass.py
66
overpass.py
@ -1,15 +1,31 @@
|
||||
import requests
|
||||
from pprint import pprint
|
||||
from models import POI
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
OVERPASS_URL = "https://overpass-api.de/api/interpreter"
|
||||
|
||||
|
||||
# REMARK:
|
||||
# zwei Strategien:
|
||||
# Fail-fast: Ein Fehler bricht alles ab → sinnvoll, wenn jedes Element kritisch ist
|
||||
# Best-effort: Fehlerhafte Elemente überspringen, Rest verarbeiten → sinnvoll bei OSM-Daten, wo einzelne Einträge unvollständig sein können
|
||||
|
||||
|
||||
class OverpassApiError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fetch_overpass(overpass_query: str, bbox: tuple) -> dict:
|
||||
def load_pois(overpass_query: str, bbox: tuple) -> list[POI]:
|
||||
"""Führt Fetch und Parse zusammen aus."""
|
||||
raw = _fetch_overpass(overpass_query=overpass_query, bbox=bbox)
|
||||
return _parse_pois(raw)
|
||||
|
||||
|
||||
def _fetch_overpass(overpass_query: str, bbox: tuple) -> dict:
|
||||
"""
|
||||
Fragt die Overpass API nach Bergbahnen in der angegebenen Bounding Box ab.
|
||||
Sendet einen HTTP-POST-Request an die Overpass API und gibt die geparste
|
||||
@ -59,7 +75,7 @@ def fetch_overpass(overpass_query: str, bbox: tuple) -> dict:
|
||||
response = requests.post(
|
||||
OVERPASS_URL,
|
||||
data={"data": query},
|
||||
timeout=5,
|
||||
timeout=15,
|
||||
headers={"User-Agent": "CDS Exercise"},
|
||||
)
|
||||
response.raise_for_status() # prüft den HTTP-Statuscode der Antwort und wirft eine Exception, wenn es ein Fehler war (requests.HTTPError)
|
||||
@ -67,7 +83,49 @@ def fetch_overpass(overpass_query: str, bbox: tuple) -> dict:
|
||||
raise OverpassApiError("Overpass-API Timeout") from exc
|
||||
except requests.RequestException as exc:
|
||||
raise OverpassApiError("Overpass-API Request fehlgeschlagen") from exc
|
||||
return response.json()
|
||||
|
||||
data = response.json()
|
||||
|
||||
# zusätzliche Fehlermöglichkeit -> Status ist zwar 200, aber Liste mit Ergebnissen ist leer...
|
||||
if "remark" in data:
|
||||
raise OverpassApiError(f"Overpass Query-Fehler: {data['remark']}")
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def _parse_poi(data: dict) -> POI:
|
||||
""" Wandelt ein einzelnes Overpass-Element in ein POI-Objekt um.
|
||||
|
||||
:param data: dictionary mit Daten für ein POI-Objekt
|
||||
:return: POI-Objekt
|
||||
"""
|
||||
try:
|
||||
return POI(
|
||||
id=data['id'],
|
||||
type=data.get('type', ''),
|
||||
lat=float(data.get("lat") or data["center"]["lat"]),
|
||||
lon=float(data.get("lon") or data["center"]["lon"]),
|
||||
tags=data.get('tags', {}),
|
||||
)
|
||||
except KeyError as exc:
|
||||
raise OverpassApiError("Feld in API - Antwort fehlt") from exc
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise OverpassApiError("API - Antwort hat falsches Format ") from exc
|
||||
|
||||
|
||||
|
||||
def _parse_pois(raw: dict) -> list[POI]:
|
||||
"""Extrahiert alle Elemente aus der API-Antwort und parst sie.
|
||||
Fehlerhafte Elemente werden übersprungen und geloggt.
|
||||
"""
|
||||
pois = []
|
||||
for element in raw.get("elements", []):
|
||||
try:
|
||||
pois.append(_parse_poi(element))
|
||||
except OverpassApiError as exc:
|
||||
logger.warning(f"POI übersprungen (id={element.get('id', '?')}): {exc}")
|
||||
return pois
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@ -86,5 +144,5 @@ if __name__ == "__main__":
|
||||
|
||||
bbox = (46.72, 9.70, 46.92, 10.00)
|
||||
# bbox = (45.8, 5.9, 47.8, 10.5)
|
||||
result = fetch_overpass(overpass_query=BERGBAHN_QUERY, bbox=bbox)
|
||||
result = load_pois(overpass_query=BERGBAHN_QUERY, bbox=bbox)
|
||||
pprint(result)
|
||||
BIN
queries/__pycache__/bergbahn.cpython-313.pyc
Normal file
BIN
queries/__pycache__/bergbahn.cpython-313.pyc
Normal file
Binary file not shown.
BIN
queries/__pycache__/restaurant.cpython-313.pyc
Normal file
BIN
queries/__pycache__/restaurant.cpython-313.pyc
Normal file
Binary file not shown.
13
queries/bergbahn.py
Normal file
13
queries/bergbahn.py
Normal file
@ -0,0 +1,13 @@
|
||||
# -> Prinzip der Trennung von Daten und Logik!
|
||||
|
||||
BERGBAHN_QUERY = """
|
||||
[out:json][timeout:2][maxsize:500000];
|
||||
(
|
||||
node["aerialway"="station"]({bbox});
|
||||
way["aerialway"="station"]({bbox});
|
||||
node["railway"="funicular"]({bbox});
|
||||
way["railway"="funicular"]({bbox});
|
||||
node["railway"="station"]["funicular"="yes"]({bbox});
|
||||
);
|
||||
out center body;
|
||||
"""
|
||||
12
queries/restaurant.py
Normal file
12
queries/restaurant.py
Normal file
@ -0,0 +1,12 @@
|
||||
# -> Prinzip der Trennung von Daten und Logik!
|
||||
|
||||
RESTAURANT_QUERY = """
|
||||
[out:json][timeout:10][maxsize:500000];
|
||||
(
|
||||
node["amenity"="restaurant"]({bbox});
|
||||
way["amenity"="restaurant"]({bbox});
|
||||
node["amenity"="cafe"]({bbox});
|
||||
way["amenity"="cafe"]({bbox});
|
||||
);
|
||||
out center body;
|
||||
"""
|
||||
Loading…
x
Reference in New Issue
Block a user