Alcove CMS
Ru

Part III, Interaction

Script posts and uploads

A trusted program reads the post as JSON and answers.

When a post needs more than one statement, a page can run a program instead: post: script: names an executable file in content/scripts/. It gets the post as JSON on stdin and answers with JSON on stdout.

The answer can hold a redirect, or values that the page is then rendered with, readable as {{ query.name }}. The script runs in the folder that holds the content folder, so it can reach data/site.db.

The live result is a word counter written in Python. Nothing is stored: the script counts and sends the numbers back.

Live result This page is rendered on request.

Words
Characters
Sentences
Longest word
Reading time
min

Source the files behind the result above

content/pages/docs-scripts.yaml

slug: docs/scripts
lang: en
title: Script posts and uploads
alcove: docs
meta:
  description: "A trusted program reads the post as JSON and answers."
  nav: docs
  eyebrow: "Part III, Interaction"
  doc: scripts
  mode: "This page is rendered on request."
post:
  script: docs/count.py
nooks:
  intro:
    - alcove: doc_scripts
  live:
    - alcove: demo_counter
  after:
    - alcove: doc_scripts_after

content/scripts/docs/count.py

#!/usr/bin/env python3
import json
import re
import sys

req = json.load(sys.stdin)
text = (req.get("values", {}).get("text") or [""])[0][:5000]
words = re.findall(r"[^\W_]+(?:['-][^\W_]+)*", text)
sentences = [s for s in re.split(r"[.!?]+", text) if s.strip()]
longest = max(words, key=len) if words else "-"
minutes = max(1, round(len(words) / 230)) if words else 0

json.dump({"values": {
    "words": str(len(words)),
    "chars": str(len(text)),
    "sentences": str(len(sentences)),
    "longest": longest,
    "minutes": str(minutes),
}}, sys.stdout)

content/alcoves/demo_counter/blueprint.html

<form class="counter" method="post" action="/docs/scripts/#live">
  {{ post.hidden }}
  <div class="field">
    <label for="ct-text">Paste a paragraph</label>
    <textarea id="ct-text" name="text" rows="5" maxlength="5000" required>{{ query.text }}</textarea>
  </div>
  <p><button class="btn btn-dark" type="submit">Count</button></p>
</form>
<dl class="facts counter-out" data-done="{{ query.words }}">
  <div><dt>Words</dt><dd>{{ query.words }}</dd></div>
  <div><dt>Characters</dt><dd>{{ query.chars }}</dd></div>
  <div><dt>Sentences</dt><dd>{{ query.sentences }}</dd></div>
  <div><dt>Longest word</dt><dd>{{ query.longest }}</dd></div>
  <div><dt>Reading time</dt><dd>{{ query.minutes }} min</dd></div>
</dl>