PyLimeRPC/pylimerpc/__init__.py

187 lines
6.5 KiB
Python
Raw Normal View History

"""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, filter_active
responses — export_responses (CSV/JSON), export_statistics
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 export_responses, export_statistics
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 .tokens import add_participants, delete_participants, list_participants
logger = logging.getLogger(__name__)
__version__ = "0.1.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)
# -- 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_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)
# -- 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",
"filter_active",
"export_responses",
"export_statistics",
"add_participants",
"list_participants",
"delete_participants",
"__version__",
]