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

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)