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:
Tammo ter Hark 2026-11-19 12:26:35 +01:00
commit d7d9dc61bf
5 changed files with 2853 additions and 14 deletions

21
examples/README.md Normal file
View file

@ -0,0 +1,21 @@
# Examples
Three minimal scripts that use `pylimerpc` the way the three
application types will. Each reads its config from `.env` and runs directly
from the repo (no `pip install -e .` needed):
| script | application model | run |
|---|---|---|
| `example_cron_export.py` | cron/URL-triggered data task | `python examples/example_cron_export.py --sid 12345 --out output/cron` |
| `example_cli.py` | distributable CLI admin tool | `python examples/example_cli.py surveys` / `export --sid 12345 --out export.csv` / `tokens-list --sid 12345` |
| `example_asgi.py` | web dashboard via ASGI router | `app` is a plain-ASGI callable; dev: `uvicorn examples.example_asgi:app --port 8000` |
See the **Prerequisites** section in the main `README.md` for what you need before
running these scripts (Python >= 3.10, a LimeSurvey 7 instance with the
RemoteControl API enabled, an RPC user account, and a filled-in `.env`).
Config: `.env` in the repo root (`LIMESURVEY_BASE_URL`, `LIMESURVEY_USERNAME`,
`LIMESURVEY_PASSWORD`, optional `LIMESURVEY_TIMEOUT_SECONDS`, `LIMESURVEY_VERIFY_SSL`).
Generated exports (`output/`, `survey_*_responses.*`, `survey_*_statistics.*`,
`*.csv`/`*.xls`/`*.xlsx`/`*.spss`) are gitignored — survey data is never synced.

4
examples/__init__.py Normal file
View file

@ -0,0 +1,4 @@
"""Example scripts that use the pylimerpc library.
See examples/README.md. Each script runs directly from the repo.
"""

103
examples/example_asgi.py Normal file
View file

@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""Example 3 — minimal plain-ASGI dashboard: active surveys as HTML.
No framework needed: ``app`` is a standard ASGI callable ``(scope, receive, send)``.
Attach it to your own router/ASGI server, e.g. (uvicorn is only a dev server):
uvicorn examples.example_asgi:app --port 8000
or directly: python examples/example_asgi.py (requires uvicorn)
Routes:
GET / → HTML table with active surveys
GET /health → "ok" (plain text)
Config is read from the .env in the repo root (independent of the working dir).
"""
from __future__ import annotations
import html
import sys
from pathlib import Path
from typing import Any, Awaitable, Callable
# Make the library importable when running this script directly from the repo.
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from pylimerpc import LsClient, LsConfig
from pylimerpc.errors import LsError
from pylimerpc.surveys import filter_active
REPO_ROOT = Path(__file__).resolve().parent.parent
Send = Callable[[dict[str, Any]], Awaitable[None]]
def load_config() -> LsConfig:
"""Config from the .env in the repo root."""
return LsConfig.from_dotenv(REPO_ROOT / ".env")
def _html_page(surveys: list[dict[str, Any]]) -> bytes:
rows = "".join(
"<tr>"
f"<td>{html.escape(str(s.get('sid', '')))}</td>"
f"<td>{html.escape(str(s.get('surveyls_title', '')))}</td>"
"</tr>"
for s in surveys
)
page = (
"<!doctype html><html><head><meta charset='utf-8'>"
"<title>LimeSurvey — active surveys</title></head><body>"
"<h1>Active surveys</h1>"
"<table border='1' cellpadding='4'><tr><th>sid</th><th>title</th></tr>"
f"{rows}</table></body></html>"
)
return page.encode("utf-8")
async def _respond(send: Send, status: int, content_type: bytes, body: bytes) -> None:
await send(
{
"type": "http.response.start",
"status": status,
"headers": [
(b"content-type", content_type),
(b"content-length", str(len(body)).encode()),
],
}
)
await send({"type": "http.response.body", "body": body})
async def app(scope: dict[str, Any], receive: Any, send: Send) -> None:
"""Plain-ASGI app; only ``http`` scopes are handled."""
if scope["type"] != "http":
return
path = scope.get("path", "/")
if path == "/health":
await _respond(send, 200, b"text/plain; charset=utf-8", b"ok")
return
if path != "/":
await _respond(send, 404, b"text/plain; charset=utf-8", b"not found")
return
try:
cfg = load_config()
with LsClient(cfg) as ls:
surveys = filter_active(ls.list_surveys())
body = _html_page(surveys)
except LsError as exc:
await _respond(send, 502, b"text/plain; charset=utf-8", f"LS error: {exc}".encode("utf-8"))
return
await _respond(send, 200, b"text/html; charset=utf-8", body)
if __name__ == "__main__":
try:
import uvicorn
except ImportError:
print("uvicorn is not installed. Attach `app` to your own ASGI server/router,")
print("or install uvicorn as a dev server: pip install uvicorn")
print(" uvicorn examples.example_asgi:app --port 8000")
raise SystemExit(1)
uvicorn.run(app, host="127.0.0.1", port=8000)

106
examples/example_cli.py Normal file
View file

@ -0,0 +1,106 @@
#!/usr/bin/env python3
"""Example 2 — distributable CLI admin tool (argparse).
python examples/example_cli.py surveys
python examples/example_cli.py export --sid 12345 --out export.csv
python examples/example_cli.py export --sid 12345 --doc-type json --out output/
python examples/example_cli.py tokens-list --sid 12345 [--limit 50] ("tokens-lijst" still works as an alias)
Config from .env (--env-file). Exit code 0 on success, 1 on error.
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
# Make the library importable when running this script directly from the repo.
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from pylimerpc import LsClient, LsConfig
from pylimerpc.errors import LsApiError, LsError
from pylimerpc.surveys import filter_active
def cmd_surveys(ls: LsClient) -> None:
surveys = filter_active(ls.list_surveys())
if not surveys:
print("No active surveys.")
return
for s in surveys:
print(f"sid={s.get('sid')}\t{s.get('surveyls_title')}")
def cmd_export(ls: LsClient, args: argparse.Namespace) -> None:
path = ls.export_responses(args.sid, doc_type=args.doc_type, output_path=args.out)
print(f"Export saved: {path} ({Path(path).stat().st_size} bytes)")
def cmd_tokens(ls: LsClient, args: argparse.Namespace) -> None:
try:
participants = ls.list_participants(args.sid, limit=args.limit)
except LsApiError as exc:
if exc.rpc_message and "participant" in exc.rpc_message.lower():
print(f"No participant table for survey {args.sid} (no tokens created yet).")
return
raise
if not participants:
print("No participants.")
return
print(f"{'tid':>6} {'email':<30} {'token':<12} completed")
for p in participants:
print(
f"{str(p.get('tid')):>6} {str(p.get('email')):<30} "
f"{str(p.get('token')):<12} {p.get('completed')}"
)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="example_cli",
description="LimeSurvey admin CLI (example of a distributable tool)",
)
parser.add_argument("--env-file", default=".env", help="path to .env (default: .env in current dir)")
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("surveys", help="show active surveys")
p_export = sub.add_parser("export", help="export responses of a survey")
p_export.add_argument("--sid", required=True, help="survey ID")
p_export.add_argument("--doc-type", default="csv", choices=["csv", "json"])
p_export.add_argument("--out", default="output", help="output file or directory")
p_tokens = sub.add_parser(
"tokens-list", aliases=["tokens-lijst"], help="show participants/tokens of a survey"
)
p_tokens.add_argument("--sid", required=True, help="survey ID")
p_tokens.add_argument("--limit", type=int, default=100)
return parser
def main() -> int:
args = build_parser().parse_args()
try:
cfg = LsConfig.from_dotenv(args.env_file)
except (ValueError, FileNotFoundError) as exc:
print(f"Config error: {exc}", file=sys.stderr)
return 1
try:
with LsClient(cfg) as ls:
if args.command == "surveys":
cmd_surveys(ls)
elif args.command == "export":
cmd_export(ls, args)
elif args.command in ("tokens-list", "tokens-lijst"):
cmd_tokens(ls, args)
except LsError as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""Example 1 — cron/URL-triggered data task: export survey responses to an output dir.
Config comes from .env (LIMESURVEY_BASE_URL/USERNAME/PASSWORD), never in code.
No interactive input; exit code 0 on success, 1 on error (suitable for cron monitoring).
Run:
.venv/bin/python examples/example_cron_export.py --sid 12345 --out output/cron
Example crontab (daily at 06:00):
0 6 * * * cd /path/to/this/repo && .venv/bin/python examples/example_cron_export.py --sid 12345 --out output/cron >> /var/log/ls-export.log 2>&1
"""
from __future__ import annotations
import argparse
import logging
import sys
from pathlib import Path
# Make the library importable when running this script directly from the repo
# (not needed after `pip install -e .`).
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from pylimerpc import LsClient, LsConfig
from pylimerpc.errors import LsError
def main() -> int:
parser = argparse.ArgumentParser(
description="Export survey responses to an output directory (cron task)."
)
parser.add_argument("--env-file", default=".env", help="path to .env (default: .env in current dir)")
parser.add_argument("--sid", required=True, help="survey ID")
parser.add_argument("--doc-type", default="csv", choices=["csv", "json"], help="export format")
parser.add_argument("--out", default="output", help="output directory (created if missing)")
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
try:
cfg = LsConfig.from_dotenv(args.env_file)
except (ValueError, FileNotFoundError) as exc:
print(f"Config error: {exc}", file=sys.stderr)
return 1
try:
with LsClient(cfg) as ls:
path = ls.export_responses(args.sid, doc_type=args.doc_type, output_path=args.out)
except LsError as exc:
print(f"Export failed: {exc}", file=sys.stderr)
return 1
path = Path(path)
print(f"OK: export saved to {path} ({path.stat().st_size} bytes)")
return 0
if __name__ == "__main__":
raise SystemExit(main())