Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d0ab53185c | |||
| 3101122975 | |||
| bc9dde71ec | |||
| bb4a2b1131 | |||
| a4d3e05253 |
26
TASK.md
26
TASK.md
@ -1,21 +1,9 @@
|
|||||||
# TASK:
|
# TASK 6:
|
||||||
|
|
||||||
Overpass-Query: -> wir wollen diesen in eine Python-Funktion `fetch_bergbahnen() in `main.py` einbauen
|
* 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.
|
||||||
|
|
||||||
```
|
* Speichert und loggt in welchen Koordinaten-Tuples ein Fehler auftritt (gebt am Schluss eine Zusammenfassung
|
||||||
[out:json][timeout:60];
|
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.
|
||||||
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;
|
|
||||||
```
|
|
||||||
|
|
||||||
* Kopiert diesen auf `https://overpass-turbo.eu/` und führt ihn mal aus.
|
|
||||||
* Spielt mit den Zoomstufen -> bbox
|
|
||||||
* Versucht mehr über bbox herauszufinden (z.B. https://wiki.openstreetmap.org/wiki/Overpass_API)
|
|
||||||
* Versucht eine einfache fetch_bergbahn() zu bauen, die API lautet "https://overpass-api.de/api/interpreter"
|
|
||||||
Nutzt dazu die request-Library in Python, wo ihr post- und get-Requests bauen könnt
|
|
||||||
BIN
__pycache__/models.cpython-313.pyc
Normal file
BIN
__pycache__/models.cpython-313.pyc
Normal file
Binary file not shown.
BIN
__pycache__/overpass.cpython-313.pyc
Normal file
BIN
__pycache__/overpass.cpython-313.pyc
Normal file
Binary file not shown.
58
main.py
58
main.py
@ -1,12 +1,56 @@
|
|||||||
from pprint import pprint
|
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__)
|
||||||
|
|
||||||
|
|
||||||
def fetch_bergbahnen(bbox) -> dict:
|
|
||||||
return {}
|
# ---------------------------------------------------------------------------
|
||||||
|
# Konfiguration
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
BBOXEN = {
|
||||||
|
"davos": (46.72, 9.70, 46.92, 10.00),
|
||||||
|
"schweiz": (45.8, 5.9, 47.8, 10.5),
|
||||||
|
}
|
||||||
|
|
||||||
|
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:
|
||||||
|
pois: list[POI] = load_pois(overpass_query=QUERY.get(query_name,""), bbox=bbox)
|
||||||
|
except OverpassApiError as exc:
|
||||||
|
logger.error(f"Fehler bei '{name}': {exc}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
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__":
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
bbox = (46.72, 9.70, 46.92, 10.00)
|
|
||||||
result = fetch_bergbahnen(bbox)
|
|
||||||
pprint(result)
|
|
||||||
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...
|
||||||
148
overpass.py
Normal file
148
overpass.py
Normal file
@ -0,0 +1,148 @@
|
|||||||
|
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 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
|
||||||
|
JSON-Antwort zurück.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
overpass_query (str): Overpass-QL-Query mit dem Platzhalter {bbox}.
|
||||||
|
Beispiel:
|
||||||
|
'[out:json][timeout:5];
|
||||||
|
(node["aerialway"="station"]({bbox}););
|
||||||
|
out center body;'
|
||||||
|
bbox (tuple): Bounding Box als 4-Tuple in Dezimalgrad:
|
||||||
|
(south, west, north, east)
|
||||||
|
Beispiel Davos: (46.72, 9.70, 46.92, 10.00)
|
||||||
|
Beispiel Schweiz: (45.8, 5.9, 47.8, 10.5)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: Geparste JSON-Antwort der Overpass API. Die Antwort enthält
|
||||||
|
unter dem Schlüssel "elements" eine Liste von OSM-Objekten
|
||||||
|
(nodes und ways) mit ihren Tags und Koordinaten.
|
||||||
|
Beispiel:
|
||||||
|
{
|
||||||
|
"elements": [
|
||||||
|
{
|
||||||
|
"type": "node",
|
||||||
|
"id": 123456,
|
||||||
|
"lat": 46.8, "lon": 9.8,
|
||||||
|
"tags": {"aerialway": "station", "name": "Jakobshorn"}
|
||||||
|
},
|
||||||
|
...
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
OverpassApiError: Wenn die API nicht innerhalb des gesetzten Timeouts
|
||||||
|
antwortet (clientseitig, unabhängig vom serverseitigen
|
||||||
|
Timeout im Query).
|
||||||
|
OverpassApiError: Wenn der Request aus einem anderen Grund fehlschlägt
|
||||||
|
(z.B. 429 Too Many Requests, 504 Gateway Timeout,
|
||||||
|
Netzwerkfehler).
|
||||||
|
"""
|
||||||
|
|
||||||
|
bbox_str = ",".join(map(str, bbox))
|
||||||
|
query = overpass_query.format(bbox=bbox_str)
|
||||||
|
|
||||||
|
try:
|
||||||
|
response = requests.post(
|
||||||
|
OVERPASS_URL,
|
||||||
|
data={"data": query},
|
||||||
|
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)
|
||||||
|
except requests.Timeout as exc:
|
||||||
|
raise OverpassApiError("Overpass-API Timeout") from exc
|
||||||
|
except requests.RequestException as exc:
|
||||||
|
raise OverpassApiError("Overpass-API Request fehlgeschlagen") from exc
|
||||||
|
|
||||||
|
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__":
|
||||||
|
|
||||||
|
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;
|
||||||
|
"""
|
||||||
|
|
||||||
|
bbox = (46.72, 9.70, 46.92, 10.00)
|
||||||
|
# bbox = (45.8, 5.9, 47.8, 10.5)
|
||||||
|
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;
|
||||||
|
"""
|
||||||
1
requirements.txt
Normal file
1
requirements.txt
Normal file
@ -0,0 +1 @@
|
|||||||
|
requests
|
||||||
Loading…
x
Reference in New Issue
Block a user