PyLimeRPC: package pylimerpc + pyproject + tests/examples (overname van minimalLS)
- nieuwe package `pylimerpc/` (rpc, session, surveys, tokens, responses, errors, utils, config) - pyproject.toml (name PyLimeRPC, versie 0.1.0) - tests/ (69 passed, 2 deselected) en examples/ - .env.example: TLS-verificatie documentatie (LIMESURVEY_VERIFY_SSL) - README/.gitignore bijgewerkt Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
parent
30fc89e4e2
commit
d7d9dc61bf
1 changed files with 2853 additions and 14 deletions
132
pylimerpc/utils.py
Normal file
132
pylimerpc/utils.py
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
"""Small shared helpers (pure functions, no state).
|
||||
|
||||
- ``to_int`` / ``is_active_flag`` / ``is_filled`` — safe parsing of LS values
|
||||
- ``parse_responses_json`` / ``decode_export_json`` — decode a JSON responses export
|
||||
- ``summary_counts`` — completed/total counts from a get_summary result
|
||||
- ``raise_for_status`` — LimeSurvey sometimes puts ``{"status": "..."}`` in the
|
||||
*result* (instead of ``error``); this detects that and raises an
|
||||
``LsApiError`` (or ``LsAuthError`` for session/auth texts).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from .errors import LsApiError, LsAuthError
|
||||
|
||||
_AUTH_STATUS_HINTS = (
|
||||
"session key",
|
||||
"invalid user",
|
||||
"password",
|
||||
"permission",
|
||||
"unauthorized",
|
||||
"not authorized",
|
||||
"login",
|
||||
)
|
||||
|
||||
|
||||
def to_int(value: Any) -> int | None:
|
||||
"""Safe conversion to int; ``None`` for empty/invalid values."""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return int(text)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def is_active_flag(value: Any) -> bool:
|
||||
"""LS ``active`` field: ``"Y"`` / ``"1"`` / ``"true"`` → True."""
|
||||
return str(value).strip().upper() in {"Y", "1", "TRUE"}
|
||||
|
||||
|
||||
def is_filled(value: Any) -> bool:
|
||||
"""Is an answer value filled (not None, empty string or ``"[]"``)?"""
|
||||
if value is None:
|
||||
return False
|
||||
if isinstance(value, str) and value.strip() == "":
|
||||
return False
|
||||
if value == "[]":
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def parse_responses_json(text: str) -> list[dict[str, Any]]:
|
||||
"""Parse a JSON responses export (already base64-decoded) into ``list[dict]``."""
|
||||
parsed = json.loads(text)
|
||||
if isinstance(parsed, dict) and isinstance(parsed.get("responses"), list):
|
||||
return parsed["responses"]
|
||||
if isinstance(parsed, list):
|
||||
return parsed
|
||||
if isinstance(parsed, dict):
|
||||
return [parsed]
|
||||
return []
|
||||
|
||||
|
||||
def decode_export_json(result: Any) -> list[dict[str, Any]]:
|
||||
"""Decode a base64 JSON ``export_responses`` result into ``list[dict]``."""
|
||||
if not isinstance(result, str) or not result:
|
||||
return []
|
||||
decoded = base64.b64decode(result)
|
||||
return parse_responses_json(decoded.decode("utf-8"))
|
||||
|
||||
|
||||
def normalize_sid(sid: Any) -> Any:
|
||||
"""Numeric sid strings → int (LS expects ``iSurveyID`` as int)."""
|
||||
as_int = to_int(sid)
|
||||
return as_int if as_int is not None else sid
|
||||
|
||||
|
||||
def summary_counts(summary: dict[str, Any]) -> tuple[int | None, int | None]:
|
||||
"""Extract (completed, total) response counts from a ``get_summary`` result.
|
||||
|
||||
Key names differ per LS version; the first match wins.
|
||||
"""
|
||||
completed = None
|
||||
total = None
|
||||
for key in ("completed_responses", "responses_completed", "completed"):
|
||||
if key in summary:
|
||||
completed = to_int(summary.get(key))
|
||||
break
|
||||
for key in ("responses", "full_responses", "responses_total", "all_responses"):
|
||||
if key in summary:
|
||||
total = to_int(summary.get(key))
|
||||
break
|
||||
return completed, total
|
||||
|
||||
|
||||
def is_status_error(result: Any) -> bool:
|
||||
"""True if ``result`` is an LS error dict: ``{"status": "..."}`` or
|
||||
``{"status": "...", "error_code": "..."}``.
|
||||
|
||||
A survey-properties dict has a ``status`` key among many other keys and
|
||||
must therefore NOT be treated as an error.
|
||||
"""
|
||||
return (
|
||||
isinstance(result, dict)
|
||||
and "status" in result
|
||||
and set(result.keys()) <= {"status", "error_code", "error"}
|
||||
)
|
||||
|
||||
|
||||
def raise_for_status(result: Any, method: str) -> Any:
|
||||
"""Raise LsApiError/LsAuthError if ``result`` is a ``{"status": ...}`` error dict.
|
||||
|
||||
Returns ``result`` unchanged otherwise.
|
||||
"""
|
||||
if is_status_error(result):
|
||||
status = str(result["status"])
|
||||
low = status.lower()
|
||||
exc_cls = LsAuthError if any(h in low for h in _AUTH_STATUS_HINTS) else LsApiError
|
||||
raise exc_cls(
|
||||
f"RPC {method!r} returned a status error: {status!r}",
|
||||
method=method,
|
||||
rpc_message=status,
|
||||
raw=result,
|
||||
)
|
||||
return result
|
||||
Loading…
Reference in a new issue