feat: enhance MediaWiki integration and error handling in SMW client
Deploy Development / deploy (push) Successful in 37s
Test Suite / lint-backend (push) Successful in 1s
Test Suite / build-frontend (push) Successful in 5s
Test Suite / playwright-tests (push) Failing after 46s

- Added MediaWiki API configuration options to docker-compose.yml for production environment.
- Improved error handling in the SMW client by introducing a response parsing method to manage API errors more effectively.
- Updated methods in the SMW client to ensure robust handling of API responses, preventing potential crashes due to unexpected data structures.
- Enhanced the import functionality to handle last imported timestamps more gracefully.
This commit is contained in:
Lars committed 2026-04-29 13:50:54 +02:00
1 parent 07b1cd8209
commit 362eb4145f
3 files changed
+71 -26

No files matched your search

+32 -15
View File
@@ -48,7 +48,11 @@ class SmwClient:
"format": "json",
})
r1.raise_for_status()
token = r1.json()["query"]["tokens"]["logintoken"]
j = self._parse_mw_response(r1.json())
tok = (((j.get("query") or {}).get("tokens") or {}).get("logintoken"))
if not tok:
raise SmwClientError("MediaWiki Login-Token fehlt in API-Antwort")
cookies = dict(r1.cookies)
# Schritt 2: Einloggen
@@ -56,10 +60,10 @@ class SmwClient:
"action": "login",
"lgname": self.user,
"lgpassword": self.password,
"lgtoken": token,
"lgtoken": tok,
}, cookies=cookies)
r2.raise_for_status()
result = r2.json()
result = self._parse_mw_response(r2.json())
if result.get("login", {}).get("result") != "Success":
reason = result.get("login", {}).get("reason", "unbekannt")
@@ -69,15 +73,31 @@ class SmwClient:
self._logged_in = True
logger.info("SMW Login erfolgreich als '%s'", self.user)
def _parse_mw_response(self, data: dict) -> dict:
"""MediaWiki liefert oft HTTP 200 mit {\"error\": {...}} — sonst KeyErrors in Client-Code."""
if not isinstance(data, dict):
raise SmwClientError("Ungültige API-Antwort (kein JSON-Objekt)")
err = data.get("error")
if isinstance(err, dict):
code = err.get("code", "")
info = err.get("info") or err.get("*") or err.get("message") or ""
raise SmwClientError(f"MediaWiki API: {code}: {info}".strip())
return data
async def _get(self, params: dict) -> dict:
"""Authentifizierter GET-Request gegen die API."""
if not self._logged_in:
await self.login()
params["format"] = "json"
async with httpx.AsyncClient(timeout=30, cookies=self._cookies) as client:
r = await client.get(self.api_url, params=params)
r.raise_for_status()
return r.json()
try:
async with httpx.AsyncClient(timeout=30, cookies=self._cookies) as client:
r = await client.get(self.api_url, params=params)
r.raise_for_status()
return self._parse_mw_response(r.json())
except SmwClientError:
raise
except Exception as e:
raise SmwClientError(str(e))
# ------------------------------------------------------------------ #
# Kategorien #
@@ -104,7 +124,8 @@ class SmwClient:
params["cmcontinue"] = cmcontinue
data = await self._get(params)
members.extend(data["query"]["categorymembers"])
q = data.get("query") or {}
members.extend(q.get("categorymembers") or [])
if "continue" in data and len(members) < limit:
cmcontinue = data["continue"].get("cmcontinue")
@@ -143,7 +164,8 @@ class SmwClient:
params["cmcontinue"] = cmcontinue
data = await self._get(params)
subcats.extend(data["query"]["categorymembers"])
q = data.get("query") or {}
subcats.extend(q.get("categorymembers") or [])
if "continue" in data:
cmcontinue = data["continue"].get("cmcontinue")
@@ -193,12 +215,9 @@ class SmwClient:
"action": "browsebysubject",
"subject": title,
})
if "error" in data:
raise SmwClientError(f"SMW Browse-Fehler für '{title}': {data['error']}")
# Normalisiere: {property_label: [wert1, wert2]}
result = {}
for prop_data in data.get("query", {}).get("data", []):
for prop_data in (data.get("query") or {}).get("data") or []:
prop_label = prop_data.get("property", "")
if prop_label.startswith("_"): # Interne SMW-Properties überspringen
continue
@@ -223,8 +242,6 @@ class SmwClient:
"action": "ask",
"query": f"{query}|limit={limit}",
})
if "error" in data:
raise SmwClientError(f"SMW Ask-Fehler: {data['error']}")
results = []
for title, props in data.get("query", {}).get("results", {}).items():