#!/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(
"
"
f"| {html.escape(str(s.get('sid', '')))} | "
f"{html.escape(str(s.get('surveyls_title', '')))} | "
"
"
for s in surveys
)
page = (
""
"LimeSurvey — active surveys"
"Active surveys
"
""
)
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)