PyLimeRPC/examples/example_asgi.py
Tammo ter Hark d7d9dc61bf 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>
2026-11-19 12:26:35 +01:00

103 lines
3.3 KiB
Python

#!/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)