Mini-Projekt: API-Anzeige
Anforderungen
- Web-Anfrage mit timeout
- JSON parsen
- Fehler abfangen
- mind. 5 Einträge formatieren
- Filter oder Zählung
- optionale Speicherung
Beispiellösung
Lösung anzeigen
import json
from urllib.request import urlopen, Request
from urllib.error import URLError, HTTPError
from pathlib import Path
def lade_todos(limit=5):
url = f"https://jsonplaceholder.typicode.com/todos?_limit={limit}"
try:
req = Request(url, headers={"User-Agent": "CodeClub/1.0"})
with urlopen(req, timeout=10) as response:
return json.loads(response.read().decode("utf-8"))
except (URLError, HTTPError, TimeoutError, json.JSONDecodeError) as e:
print("Konnte Daten nicht laden:", e)
return []
print("=== API-Anzeige ===")
todos = lade_todos(8)
if not todos:
print("Keine Daten.")
else:
offen = 0
for t in todos:
mark = "x" if t["completed"] else " "
if not t["completed"]:
offen += 1
print(f"[{mark}] {t['id']}: {t['title']}")
print(f"Offen: {offen} / {len(todos)}")
Path("todos_cache.json").write_text(
json.dumps(todos, indent=2, ensure_ascii=False),
encoding="utf-8",
)
print("Cache gespeichert.")
Kapitel 39 geschafft!
Als Nächstes: Type Hints und Dataclasses – Code, der sich selbst erklärt.