PyLimeRPC 0.2.0 — prompts.md Prompt 1-4

- responses.py: get_summary() (raw RPC get_summary), count_responses() ->
  frozen ResponseCounts(completed, incomplete, total), export_responses_auto()
  with automatic format fallback (xlsx -> xls -> csv) on IWriter errors
- utils.py: summary_counts_full() -> (completed, incomplete, total) with
  per-LS-version key fallbacks; summary_counts left untouched
- surveys.py: get_survey_by_sid() (dict | None), get_survey_info() ->
  frozen SurveyInfo(sid, title, active)
- tokens.py: documented that extra/custom token attributes (attribute_1, ...)
  pass through unchanged in add_participants/list_participants
- LsClient: get_summary, count_responses, get_survey_by_sid, get_survey_info,
  export_responses_auto; __all__ + re-exports updated
- README: new "Response counts & summary" section + usage examples
- .gitignore: prompts.md added (local-only docs, like werkdocument.md)
- version 0.1.0 -> 0.2.0 (__init__.py + pyproject.toml)
- tests: +27 FakeRpc unit tests (96 passed, 2 deselected)

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
Tammo ter Hark 2026-11-20 11:56:03 +01:00
commit 6822eab467
5 changed files with 633 additions and 24 deletions

View file

@ -16,8 +16,8 @@ Modules:
config — settings from .env / environment variables (LsConfig)
rpc — JSON-RPC transport (rpc_call, RpcClient, endpoint_url)
session — session keys: get_session_key / release_session_key
surveys — list_surveys, get_survey_properties, filter_active
responses — export_responses (CSV/JSON), export_statistics
surveys — list_surveys, get_survey_properties, get_survey_by_sid, get_survey_info, filter_active
responses — export_responses (CSV/JSON), export_responses_auto, export_statistics, get_summary, count_responses
tokens — token management (participants): add / list / delete
errors — custom exceptions (LsError, LsConnectionError, LsApiError, LsAuthError)
utils — small shared helpers
@ -38,15 +38,29 @@ from . import surveys as _surveys
from . import tokens as _tokens
from .config import LsConfig
from .errors import LsApiError, LsAuthError, LsConnectionError, LsError
from .responses import export_responses, export_statistics
from .responses import (
ResponseCounts,
count_responses,
export_responses,
export_responses_auto,
export_statistics,
get_summary,
)
from .rpc import RpcClient, endpoint_url, rpc_call
from .session import get_session_key, release_session_key
from .surveys import filter_active, get_survey_properties, list_surveys
from .surveys import (
SurveyInfo,
filter_active,
get_survey_by_sid,
get_survey_info,
get_survey_properties,
list_surveys,
)
from .tokens import add_participants, delete_participants, list_participants
logger = logging.getLogger(__name__)
__version__ = "0.1.0"
__version__ = "0.2.0"
class LsClient:
@ -123,6 +137,25 @@ class LsClient:
"""Properties of a single survey (see ``surveys.get_survey_properties``)."""
return _surveys.get_survey_properties(self.rpc, self._require_key(), sid, properties=properties)
def get_survey_by_sid(
self,
sid: int | str,
owner_id: int | str | None = None,
group_id: int | str | None = None,
) -> dict[str, Any] | None:
"""Find one survey by sid (see ``surveys.get_survey_by_sid``); ``None`` if it does not exist."""
return _surveys.get_survey_by_sid(
self.rpc,
self._require_key(),
sid,
owner_id=owner_id if owner_id is not None else self.config.owner_id,
group_id=group_id if group_id is not None else self.config.group_id,
)
def get_survey_info(self, sid: int | str) -> SurveyInfo | None:
"""Compact info (sid/title/active) of a survey (see ``surveys.get_survey_info``)."""
return _surveys.get_survey_info(self.rpc, self._require_key(), sid)
# -- responses / statistics ---------------------------------------
def export_responses(
@ -134,6 +167,18 @@ class LsClient:
"""Export responses of a survey (see ``responses.export_responses``)."""
return _responses.export_responses(self.rpc, self._require_key(), sid, doc_type, **kwargs)
def export_responses_auto(
self,
sid: int | str,
formats: Iterable[str] = ("xlsx", "xls", "csv"),
**kwargs: Any,
) -> tuple[bytes | Path, str]:
"""Export responses with automatic format fallback (see ``responses.export_responses_auto``).
Returns ``(data, used_format)``.
"""
return _responses.export_responses_auto(self.rpc, self._require_key(), sid, formats, **kwargs)
def export_statistics(
self,
sid: int | str,
@ -143,6 +188,16 @@ class LsClient:
"""Export statistics of a survey (see ``responses.export_statistics``)."""
return _responses.export_statistics(self.rpc, self._require_key(), sid, doc_type, **kwargs)
# -- summary / response-tellingen -----------------------------------
def get_summary(self, sid: int | str) -> dict[str, Any]:
"""Raw ``get_summary`` result of a survey (see ``responses.get_summary``)."""
return _responses.get_summary(self.rpc, self._require_key(), sid)
def count_responses(self, sid: int | str) -> ResponseCounts:
"""Response counts (completed/incomplete/total) of a survey (see ``responses.count_responses``)."""
return _responses.count_responses(self.rpc, self._require_key(), sid)
# -- tokens (participants) ------------------------------------------
def add_participants(
@ -177,9 +232,16 @@ __all__ = [
"release_session_key",
"list_surveys",
"get_survey_properties",
"get_survey_by_sid",
"get_survey_info",
"SurveyInfo",
"filter_active",
"export_responses",
"export_responses_auto",
"export_statistics",
"get_summary",
"count_responses",
"ResponseCounts",
"add_participants",
"list_participants",
"delete_participants",

View file

@ -6,22 +6,33 @@ LS7 RemoteControl methods called here (lay these next to the API docs):
completion_status, field_map, header]``; the result is **base64-encoded**
- ``export_statistics`` — params ``[session_key, sid, doc_type, language]``;
also **base64-encoded**
- ``get_summary`` — params ``[session_key, sid]``; result is a dict with,
among other things, the response counts
Both functions decode the base64 and return ``bytes``; with ``output_path``
the file is written and the ``Path`` is returned (if ``output_path`` is an
existing directory, a default name ``survey_<sid>_responses.<ext>`` is used).
``export_responses_auto`` tries several ``doc_type`` formats in order and falls
back on the next one when the LS installation lacks a writer (e.g. the xlsx
writer: "Writer for xlsx should implement IWriter").
Both export functions decode the base64 and return ``bytes``; with
``output_path`` the file is written and the ``Path`` is returned (if
``output_path`` is an existing directory, a default name
``survey_<sid>_responses.<ext>`` is used).
"""
from __future__ import annotations
import base64
import binascii
import logging
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from typing import Any, Iterable
from .errors import LsApiError
from .rpc import RpcClient
from .utils import normalize_sid, parse_responses_json, raise_for_status
from .utils import normalize_sid, parse_responses_json, raise_for_status, summary_counts_full
logger = logging.getLogger(__name__)
def _decode_base64(result: Any, method: str) -> bytes:
@ -103,6 +114,56 @@ def export_responses(
return data
def export_responses_auto(
client: RpcClient,
session_key: str,
sid: int | str,
formats: Iterable[str] = ("xlsx", "xls", "csv"),
**kwargs: Any,
) -> tuple[bytes | Path, str]:
"""Export responses, trying the formats in order until one works.
Not every LS installation has every export writer installed — for example
the xlsx writer may be missing, in which case LS returns an error like
"Writer for xlsx should implement IWriter". This function tries each
format in ``formats`` and falls back to the next one on exactly that error
(an ``LsApiError`` whose message or ``rpc_message`` contains ``"IWriter"``);
any other error is raised immediately.
Args:
client: an ``RpcClient``.
session_key: a valid session key.
sid: survey ID.
formats: doc types to try, in order (default ``("xlsx", "xls", "csv")``).
**kwargs: passed to ``export_responses`` (e.g. ``output_path``).
Returns:
``(data, used_format)`` — ``data`` as ``bytes``, or ``Path`` when
``output_path`` was given; ``used_format`` is the ``doc_type`` that worked.
Raises:
LsApiError: when every format fails with an IWriter error (the last one
is re-raised), or immediately on any other error.
"""
last_exc: LsApiError | None = None
for doc_type in formats:
try:
data = export_responses(client, session_key, sid, doc_type, **kwargs)
except LsApiError as exc:
if "IWriter" in str(exc) or "IWriter" in str(exc.rpc_message or ""):
last_exc = exc
logger.debug("export_responses doc_type=%r unavailable (%s); trying next format", doc_type, exc)
continue
raise
return data, doc_type
if last_exc is not None:
raise last_exc
raise LsApiError(
f"export_responses_auto: no formats to try: {formats!r}",
method="export_responses_auto",
)
def export_responses_json(
client: RpcClient,
session_key: str,
@ -152,3 +213,57 @@ def export_statistics(
if output_path is not None:
return _write_output(data, output_path, f"survey_{sid}_statistics.{_ext(doc_type)}")
return data
@dataclass(frozen=True)
class ResponseCounts:
"""Response counts of a survey.
Fields: ``completed`` (finished), ``incomplete`` (in progress) and ``total``.
"""
completed: int
incomplete: int
total: int
def get_summary(client: RpcClient, session_key: str, sid: int | str) -> dict[str, Any]:
"""Raw RPC ``get_summary`` — summary of a survey.
LS7 RPC method: ``get_summary`` with params ``[session_key, sid]``.
Args:
client: an ``RpcClient``.
session_key: a valid session key.
sid: survey ID (a numeric string is normalized to int).
Returns:
The summary dict (contains, among other things, the response counts).
Raises:
LsApiError: on a ``{"status": ...}`` error or if the result is not a dict.
"""
params: list[Any] = [session_key, normalize_sid(sid)]
result = client.call("get_summary", params)
raise_for_status(result, "get_summary")
if not isinstance(result, dict):
raise LsApiError(
f"RPC 'get_summary' returned no dict: {result!r}",
method="get_summary",
raw=result,
)
return result
def count_responses(client: RpcClient, session_key: str, sid: int | str) -> ResponseCounts:
"""Count the responses of a survey via ``get_summary``.
Reads the counts from the summary dict (key names differ per LS version;
missing/invalid values count as 0) — see ``utils.summary_counts_full``.
Returns:
``ResponseCounts(completed, incomplete, total)``.
"""
summary = get_summary(client, session_key, sid)
completed, incomplete, total = summary_counts_full(summary)
return ResponseCounts(completed=completed, incomplete=incomplete, total=total)

View file

@ -5,11 +5,16 @@
``group_id`` filters client-side on ``group_id``/``gsid`` when present)
- ``get_survey_properties(client, session_key, sid, properties=None)`` —
properties dict of a single survey
- ``get_survey_by_sid(client, session_key, sid, owner_id=None, group_id=None)`` —
one survey dict from ``list_surveys`` by sid, or ``None``
- ``get_survey_info(client, session_key, sid)`` — compact ``SurveyInfo``
(sid/title/active), or ``None`` when the survey does not exist
- ``filter_active(surveys)`` — only active surveys (``active == "Y"``)
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Iterable
from .errors import LsApiError
@ -99,3 +104,71 @@ def get_survey_properties(
def filter_active(surveys: Iterable[dict[str, Any]]) -> list[dict[str, Any]]:
"""Filter a survey list to active surveys only (``active == "Y"``)."""
return [s for s in surveys if is_active_flag(s.get("active"))]
@dataclass(frozen=True)
class SurveyInfo:
"""Compact info about a survey, built from a ``list_surveys`` entry.
Fields: ``sid``, ``title`` (``surveyls_title``) and ``active``.
"""
sid: int
title: str
active: bool
def get_survey_by_sid(
client: RpcClient,
session_key: str,
sid: int | str,
owner_id: int | str | None = None,
group_id: int | str | None = None,
) -> dict[str, Any] | None:
"""Find one survey by sid in the ``list_surveys`` result.
Args:
client: an ``RpcClient``.
session_key: a valid session key.
sid: survey ID to look for (matched as ``str(sid)`` against each entry).
owner_id: optional, passed through to ``list_surveys``.
group_id: optional, passed through to ``list_surveys``.
Returns:
The survey dict, or ``None`` when no survey with this sid exists —
"does not exist" is NOT an exception.
Raises:
LsAuthError / LsApiError: propagated from ``list_surveys`` (e.g. a
``{"status": ...}`` result is raised via ``raise_for_status``).
"""
surveys = list_surveys(client, session_key, owner_id=owner_id, group_id=group_id)
for survey in surveys:
if str(survey.get("sid")) == str(sid):
return survey
return None
def get_survey_info(client: RpcClient, session_key: str, sid: int | str) -> SurveyInfo | None:
"""Compact info (sid / title / active) of a survey.
Built from ``get_survey_by_sid``; handy for apps that want "does not exist /
not active / title" in a single call.
Returns:
``SurveyInfo(sid, title, active)``, or ``None`` when the survey does not exist.
"""
survey = get_survey_by_sid(client, session_key, sid)
if survey is None:
return None
sid_int = to_int(survey.get("sid"))
if sid_int is None:
sid_int = to_int(sid) or 0
title = survey.get("surveyls_title")
if title is None:
title = survey.get("title")
return SurveyInfo(
sid=sid_int,
title=str(title) if title is not None else "",
active=is_active_flag(survey.get("active")),
)

View file

@ -9,7 +9,10 @@ LS7 RemoteControl methods called here (lay these next to the API docs):
- ``delete_participants`` — params ``[session_key, sid, [token_ids]]``
Each participant is a dict with e.g. ``email``, ``firstname``, ``lastname``,
``token`` (``token`` is generated by LS on add_participants).
``token`` (``token`` is generated by LS on add_participants). Surveys can define
**extra (custom) token attributes** (``attribute_1``, ``attribute_2``, ...);
those keys are passed through verbatim in both directions — on add they are
sent along in the participant dict, on list they are part of the returned dicts.
"""
from __future__ import annotations
@ -39,6 +42,8 @@ def add_participants(
session_key: a valid session key.
sid: survey ID.
participants: list of dicts, e.g. ``[{"email": "a@b.c", "firstname": "A"}]``.
Extra/custom token attributes (``attribute_1``, ...) may be included
as extra keys; they are sent to LS unchanged.
create_token: optional; if False, no token is created.
Returns:
@ -70,7 +75,9 @@ def list_participants(
``[session_key, sid, start, limit]`` (+ optional ``conditions``, ``language``).
Returns:
List of participant dicts (``tid``, ``email``, ``token``, ``completed``, ...).
List of participant dicts (``tid``, ``email``, ``token``, ``completed``, ...,
plus any extra/custom token attributes such as ``attribute_1`` — returned
unchanged, exactly as LS sends them).
"""
params: list[Any] = [session_key, normalize_sid(sid), int(start), int(limit)]
if conditions is not None:

View file

@ -3,6 +3,7 @@
- ``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
- ``summary_counts_full`` — (completed, incomplete, total) 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).
@ -100,6 +101,31 @@ def summary_counts(summary: dict[str, Any]) -> tuple[int | None, int | None]:
return completed, total
def _summary_int(summary: dict[str, Any], keys: tuple[str, ...]) -> int:
"""First present key of ``keys`` as int; missing/invalid → 0."""
for key in keys:
if key in summary:
value = to_int(summary[key])
return value if value is not None else 0
return 0
def summary_counts_full(summary: dict[str, Any]) -> tuple[int, int, int]:
"""Extract (completed, incomplete, total) from a ``get_summary`` result.
Key names differ per LS version; the first present key wins:
``completed_responses`` (fallback ``responses_completed`` / ``completed``) and
``incomplete_responses`` (fallback ``in_progress_responses``). ``total`` is
``full_responses`` when present, else ``completed + incomplete``.
Missing or invalid values count as 0.
"""
completed = _summary_int(summary, ("completed_responses", "responses_completed", "completed"))
incomplete = _summary_int(summary, ("incomplete_responses", "in_progress_responses"))
full = to_int(summary["full_responses"]) if "full_responses" in summary else None
total = full if full is not None else completed + incomplete
return completed, incomplete, total
def is_status_error(result: Any) -> bool:
"""True if ``result`` is an LS error dict: ``{"status": "..."}`` or
``{"status": "...", "error_code": "..."}``.