106 lines
3.6 KiB
Python
106 lines
3.6 KiB
Python
|
|
#!/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())
|