- 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>
249 lines
8.6 KiB
Python
249 lines
8.6 KiB
Python
"""PyLimeRPC — reusable client library for LimeSurvey (import package: ``pylimerpc``).
|
|
|
|
Talks to the LimeSurvey RemoteControl JSON-RPC API (LS7, endpoint
|
|
``index.php?r=admin/remotecontrol``). Python standard library only.
|
|
|
|
Usage (session is opened/closed automatically):
|
|
|
|
from pylimerpc import LsClient, LsConfig
|
|
|
|
cfg = LsConfig.from_dotenv(".env")
|
|
with LsClient(cfg) as ls:
|
|
surveys = ls.list_surveys()
|
|
props = ls.get_survey_properties(surveys[0]["sid"])
|
|
|
|
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, 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
|
|
|
|
Credentials never live in code or git, only in a .env file or as parameters.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from pathlib import Path
|
|
from types import TracebackType
|
|
from typing import Any, Iterable
|
|
|
|
from . import responses as _responses
|
|
from . import session as _session
|
|
from . import surveys as _surveys
|
|
from . import tokens as _tokens
|
|
from .config import LsConfig
|
|
from .errors import LsApiError, LsAuthError, LsConnectionError, LsError
|
|
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 (
|
|
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.2.0"
|
|
|
|
|
|
class LsClient:
|
|
"""Main client with session management.
|
|
|
|
Opens a session on ``__enter__`` (``get_session_key``) and releases the
|
|
key on ``__exit__`` (also on exception):
|
|
|
|
cfg = LsConfig.from_dotenv(".env")
|
|
with LsClient(cfg) as ls:
|
|
surveys = ls.list_surveys()
|
|
|
|
Args:
|
|
config: an ``LsConfig`` (base_url, username, password, timeout, ...).
|
|
rpc: optional own ``RpcClient`` (handy for tests); by default one is
|
|
built from ``config``.
|
|
"""
|
|
|
|
def __init__(self, config: LsConfig, *, rpc: RpcClient | None = None) -> None:
|
|
self.config = config
|
|
self.rpc = rpc if rpc is not None else RpcClient.from_config(config)
|
|
self.session_key: str | None = None
|
|
|
|
def __enter__(self) -> LsClient:
|
|
self.session_key = _session.get_session_key(
|
|
self.rpc, self.config.username, self.config.password
|
|
)
|
|
logger.debug("Session opened (key ends with ...%s)", self.session_key[-4:])
|
|
return self
|
|
|
|
def __exit__(
|
|
self,
|
|
exc_type: type[BaseException] | None,
|
|
exc: BaseException | None,
|
|
tb: TracebackType | None,
|
|
) -> None:
|
|
self.close()
|
|
|
|
def close(self) -> None:
|
|
"""Release the session key (safe to call repeatedly; errors are only logged)."""
|
|
if self.session_key:
|
|
try:
|
|
_session.release_session_key(self.rpc, self.session_key)
|
|
except LsError as exc:
|
|
logger.debug("release_session_key failed (ignored): %s", exc)
|
|
finally:
|
|
self.session_key = None
|
|
|
|
def _require_key(self) -> str:
|
|
if not self.session_key:
|
|
raise LsError("No active session — use 'with LsClient(cfg) as ls:'")
|
|
return self.session_key
|
|
|
|
# -- surveys ------------------------------------------------------
|
|
|
|
def list_surveys(
|
|
self,
|
|
owner_id: int | str | None = None,
|
|
group_id: int | str | None = None,
|
|
) -> list[dict[str, Any]]:
|
|
"""List of surveys (see ``surveys.list_surveys``)."""
|
|
return _surveys.list_surveys(
|
|
self.rpc,
|
|
self._require_key(),
|
|
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_properties(
|
|
self,
|
|
sid: int | str,
|
|
properties: Iterable[str] | None = None,
|
|
) -> dict[str, Any]:
|
|
"""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(
|
|
self,
|
|
sid: int | str,
|
|
doc_type: str = "json",
|
|
**kwargs: Any,
|
|
) -> bytes | Path:
|
|
"""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,
|
|
doc_type: str = "json",
|
|
**kwargs: Any,
|
|
) -> bytes | Path:
|
|
"""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(
|
|
self,
|
|
sid: int | str,
|
|
participants: list[dict[str, Any]],
|
|
**kwargs: Any,
|
|
) -> Any:
|
|
"""Add participants (see ``tokens.add_participants``)."""
|
|
return _tokens.add_participants(self.rpc, self._require_key(), sid, participants, **kwargs)
|
|
|
|
def list_participants(self, sid: int | str, **kwargs: Any) -> list[dict[str, Any]]:
|
|
"""List participants (see ``tokens.list_participants``)."""
|
|
return _tokens.list_participants(self.rpc, self._require_key(), sid, **kwargs)
|
|
|
|
def delete_participants(self, sid: int | str, token_ids: list[int | str]) -> Any:
|
|
"""Delete participants (see ``tokens.delete_participants``)."""
|
|
return _tokens.delete_participants(self.rpc, self._require_key(), sid, token_ids)
|
|
|
|
|
|
__all__ = [
|
|
"LsClient",
|
|
"LsConfig",
|
|
"RpcClient",
|
|
"rpc_call",
|
|
"endpoint_url",
|
|
"LsError",
|
|
"LsConnectionError",
|
|
"LsApiError",
|
|
"LsAuthError",
|
|
"get_session_key",
|
|
"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",
|
|
"__version__",
|
|
]
|