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