GitHub

Example: Blog

A Model, server functions, route parameters, 404s and validation errors.

  • 87 lines of Python
  • 2 pages
  • 1 server function
  • 2184 B page JS (gzip)
This example needs its server (database, sessions or server functions). Run it locally:
Terminal
pyweb dev examples/blog/app.pyweb

#Source

examples/blog/app.pyweb
"""Blog: a Model, server functions, server-rendered pages, route params."""

from pyweb import App, Field, Model, RPCError, component, server
from pyweb.ui import Button, Card, CardContent, CardDescription, CardHeader

app = App(title="PyWeb Blog", database="sqlite:///blog.db", stylesheets=["/static/app.css"])


class Article(Model):
    title: str = Field(max=200)
    body: str = ""


def all_posts():
    return [a.to_dict() for a in Article.query().order("-id")]


@server
def publish(title: str, body: str) -> list:
    title, body = title.strip(), body.strip()
    if not title or not body:
        raise RPCError("validation_error", "A post needs a title and a body.")
    Article.create(title=title, body=body)
    return all_posts()


@component
def PostCard(post):
    <article class="pw-card post" animate="fade-up">
        <h2><a href={"/posts/" + str(post["id"])}>{post["title"]}</a></h2>
        <p class="muted">{post["body"][:140]}</p>
    </article>


@app.page("/", title="PyWeb Blog")
def Home():
    posts = all_posts()
    title = ""
    body = ""
    error = ""

    def submit():
        try:
            posts = publish(title, body)
            title = ""
            body = ""
            error = ""
        except RPCError as e:
            error = str(e)

    <main>
        <h1>Blog</h1>
        <Card>
            <CardHeader>
                <h2 data-part="title">New post</h2>
                <CardDescription>Saved with a server function; the list re-renders from its answer.</CardDescription>
            </CardHeader>
            <CardContent>
                <form class="stack" onsubmit={submit}>
                    <input id="title" class="pw-control" bind={title} placeholder="Title" aria-label="Title" />
                    <textarea id="body" class="pw-control" bind={body} placeholder="Write something…"
                              aria-label="Post"></textarea>
                    <p class="error" id="error" role="alert">{error}</p>
                    <div><Button id="publish" type="submit">Publish</Button></div>
                </form>
            </CardContent>
        </Card>
        <div class="posts">
            for post in posts:
                <PostCard post={post} />
            if not posts:
                <p class="empty">No posts yet.</p>
        </div>
    </main>


@app.page("/posts/{post_id}")
def Post(post_id: int):
    post = Article.get_or_404(post_id)

    <main>
        <p><Button href="/" variant="ghost" size="sm">← All posts</Button></p>
        <article class="pw-card post" animate="fade-up">
            <h1>{post.title}</h1>
            <p>{post.body}</p>
        </article>
    </main>

#What runs where

Output of pyweb inspect: every page variable, handler and server function, where it runs and why.

Output
page Home  route=/
  browser  posts          reactive state: assigned in submit(); initial value computed on the server and sent
  browser  title          reactive state: bound to an input (line 60); literal initial value
  browser  body           reactive state: bound to an input (line 61); literal initial value
  browser  error          reactive state: assigned in submit(); literal initial value
  browser  submit         event handler (compiled to JavaScript)
page Post  route=/posts/{post_id}
  server   post           computed per request on the server; value sent because browser code reads it
rpc POST /__pyweb/rpc/publish  (title: str, body: str) -> list

#Generated JavaScript

The browser modules the compiler wrote (before minification). They import the shared runtime.

JavaScript
// Home.js
import { h as $h, t as $t, dyn as $dyn, list as $list, when as $when, signal as $signal, computed as $computed, mount as $mount, onMount as $onMount, py as $py, rpc as $rpc, slot as $slot, onCleanup as $onCleanup, spreadProps as $spreadProps } from "./runtime.js";
// card.pyweb
const { Card, CardHeader, CardDescription, CardContent } = (() => {
  function Card($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("div", {"class": "pw-card", "data-pw-ui": "card", "data-part": "card", "$spread3": () => attrs()}, () => [$dyn(() => children())])];
  }
  function CardHeader($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("div", {"data-part": "header", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
  }
  function CardDescription($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("p", {"data-part": "description", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
  }
  function CardContent($p) {
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    return [$h("div", {"data-part": "content", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
  }
  return { Card, CardHeader, CardDescription, CardContent };
})();
// button.pyweb
const { Button } = (() => {
  function Button($p) {
    const variant = $p["variant"] || (() => "default");
    const size = $p["size"] || (() => "md");
    const type = $p["type"] || (() => "button");
    const href = $p["href"] || (() => null);
    const loading = $p["loading"] || (() => false);
    const disabled = $p["disabled"] || (() => false);
    const onclick = $p["onclick"] || (() => null);
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    const busy = $computed(() => ($py.truth(loading()) ? "true" : null));
    const part = $computed(() => $py.or($py.m(attrs(), "get", "data-part"), () => "button"));
    return [$when(() => $py.truth(href()), () => [$h("a", {"class": "pw-button", "data-part": () => part(), "data-variant": () => variant(), "data-size": () => size(), "href": () => href(), "aria-disabled": () => ($py.truth(disabled()) ? "true" : null), "onclick": (e) => { const f = onclick(); return f ? f(e) : undefined; }, "$spread7": () => attrs()}, () => [$dyn(() => children())])], () => [$h("button", {"class": "pw-button", "data-part": () => part(), "data-variant": () => variant(), "data-size": () => size(), "type": () => type(), "disabled": () => $py.or(disabled(), () => loading()), "aria-busy": () => busy(), "onclick": (e) => { const f = onclick(); return f ? f(e) : undefined; }, "$spread8": () => attrs()}, () => [
          $when(() => $py.truth(loading()), () => [$h("span", {"class": "pw-spinner", "aria-hidden": "true"})]),
          $dyn(() => children())
        ])])];
  }
  return { Button };
})();
function PostCard($p) {
  const post = $p["post"] || (() => null);
  return [$h("article", {"class": "pw-card post", "data-pw-motion": JSON.stringify({"animate": "fade-up"}), "style": ((i, s) => s)(null, null, null, "fade-up")}, () => [
      $h("h2", null, () => [$h("a", {"href": () => $py.add("/posts/", $py.str($py.at(post(), "id")))}, () => [$dyn(() => $py.at(post(), "title"))])]),
      $h("p", {"class": "muted"}, () => [$dyn(() => $py.slice($py.at(post(), "body"), null, 140, null))])
    ])];
}
function Home($s) {
  const posts = $signal("posts" in $s ? $s["posts"] : null, "posts");
  const title = $signal("title" in $s ? $s["title"] : "", "title");
  const body = $signal("body" in $s ? $s["body"] : "", "body");
  const error = $signal("error" in $s ? $s["error"] : "", "error");
  async function submit() {
    let e;
    try {
      posts((await $rpc("publish", {"title": title(), "body": body()})));
      title("");
      body("");
      error("");
    } catch ($err) {
      if ($py.exc($err, ["RPCError"])) {
        e = $err;
        error($py.str(e));
      } else { throw $err; }
    }
  }
  return [$h("main", null, () => [
      $h("h1", null, () => [$t("Blog")]),
      Card({"children": () => [
        CardHeader({"children": () => [
          $h("h2", {"data-part": "title"}, () => [$t("New post")]),
          CardDescription({"children": () => [$t("Saved with a server function; the list re-renders from its answer.")]})
        ]}),
        CardContent({"children": () => [$h("form", {"class": "stack", "onsubmit": submit}, () => [
            $h("input", {"id": "title", "class": "pw-control", "$bind": title, "placeholder": "Title", "aria-label": "Title"}),
            $h("textarea", {"id": "body", "class": "pw-control", "$bind": body, "placeholder": "Write something\u2026", "aria-label": "Post"}),
            $h("p", {"class": "error", "id": "error", "role": "alert"}, () => [$dyn(() => error())]),
            $h("div", null, () => [Button({"type": () => "submit", "children": () => [$t("Publish")], "$rest": () => ({"id": "publish"})})])
          ])]})
      ]}),
      $h("div", {"class": "posts"}, () => [
        $list(() => posts(), (post) => [PostCard({"post": () => post})]),
        $when(() => !$py.truth(posts()), () => [$h("p", {"class": "empty"}, () => [$t("No posts yet.")])])
      ])
    ])];
}
$mount("Home", Home);


// Post.js
import { h as $h, t as $t, dyn as $dyn, list as $list, when as $when, signal as $signal, computed as $computed, mount as $mount, onMount as $onMount, py as $py, rpc as $rpc, slot as $slot, onCleanup as $onCleanup, spreadProps as $spreadProps } from "./runtime.js";
// button.pyweb
const { Button } = (() => {
  function Button($p) {
    const variant = $p["variant"] || (() => "default");
    const size = $p["size"] || (() => "md");
    const type = $p["type"] || (() => "button");
    const href = $p["href"] || (() => null);
    const loading = $p["loading"] || (() => false);
    const disabled = $p["disabled"] || (() => false);
    const onclick = $p["onclick"] || (() => null);
    const children = $p["children"] || (() => null);
    const attrs = $p["$rest"] || (() => ({}));
    const busy = $computed(() => ($py.truth(loading()) ? "true" : null));
    const part = $computed(() => $py.or($py.m(attrs(), "get", "data-part"), () => "button"));
    return [$when(() => $py.truth(href()), () => [$h("a", {"class": "pw-button", "data-part": () => part(), "data-variant": () => variant(), "data-size": () => size(), "href": () => href(), "aria-disabled": () => ($py.truth(disabled()) ? "true" : null), "onclick": (e) => { const f = onclick(); return f ? f(e) : undefined; }, "$spread7": () => attrs()}, () => [$dyn(() => children())])], () => [$h("button", {"class": "pw-button", "data-part": () => part(), "data-variant": () => variant(), "data-size": () => size(), "type": () => type(), "disabled": () => $py.or(disabled(), () => loading()), "aria-busy": () => busy(), "onclick": (e) => { const f = onclick(); return f ? f(e) : undefined; }, "$spread8": () => attrs()}, () => [
          $when(() => $py.truth(loading()), () => [$h("span", {"class": "pw-spinner", "aria-hidden": "true"})]),
          $dyn(() => children())
        ])])];
  }
  return { Button };
})();
function Post($s) {
  const post = $s["post"];
  return [$h("main", null, () => [
      $h("p", null, () => [Button({"href": () => "/", "variant": () => "ghost", "size": () => "sm", "children": () => [$t("\u2190 All posts")]})]),
      $h("article", {"class": "pw-card post", "data-pw-motion": JSON.stringify({"animate": "fade-up"}), "style": ((i, s) => s)(null, null, null, "fade-up")}, () => [
        $h("h1", null, () => [$t($py.text(post.title))]),
        $h("p", null, () => [$t($py.text(post.body))])
      ])
    ])];
}
$mount("Post", Post);
Edit this page on GitHub