Example: Chat rooms
Route parameters, shared server state and live updates with publish() and subscribe().
- 100 lines of Python
- 2 pages
- 2 server functions
- 2166 B page JS (gzip)
This example needs its server (database, sessions or server functions). Run it locally:
Terminal
pyweb dev examples/chat/app.pyweb#Source
examples/chat/app.pyweb
"""Chat rooms: route parameters, server state and live updates."""
import itertools
import threading
from pyweb import App, RPCError, channel, publish, server, subscribe
from pyweb.ui import Avatar, Badge, Button, Card, CardContent
app = App(title="Chat", stylesheets=["/static/app.css"])
ROOMS = ["general", "python", "random"]
_messages = {room: [] for room in ROOMS}
_ids = itertools.count(1)
_lock = threading.Lock()
def _room(room):
if room not in _messages:
raise RPCError("not_found", f"no room named {room!r}")
return _messages[room]
@server
def history(room: str, after: int = 0) -> list:
return [m for m in _room(room) if m["id"] > after][-100:]
@server
def send(room: str, author: str, text: str) -> None:
text = text.strip()
if not text:
return
with _lock:
message = {"id": next(_ids), "author": author.strip() or "guest", "text": text[:500]}
_room(room).append(message)
publish("chat:" + room, message) # every open page for this room receives it
def room_list():
return [{"name": room, "count": len(_messages[room])} for room in ROOMS]
@app.page("/", title="Chat rooms")
def Lobby():
rooms = room_list()
<main>
<h1>Rooms</h1>
<ul class="rooms">
for room in rooms:
<li animate="fade-up">
<a class="pw-card room" href={"/chat/" + room["name"]}>
<b>#{room["name"]}</b>
<Badge variant="secondary">{room["count"]} messages</Badge>
</a>
</li>
</ul>
</main>
@app.page("/chat/{room}", title="Chat")
def Room(room: str):
messages = history(room)
feed = channel("chat:" + room) # signed on the server; lets this page listen
author = "guest"
draft = ""
def received(message):
messages = messages + [message]
def on_mount():
subscribe(feed, received)
def submit():
if draft.strip():
send(room, author, draft)
draft = ""
<main>
<p><Button href="/" variant="ghost" size="sm">← Rooms</Button></p>
<h1>#{room}</h1>
<Card>
<CardContent>
<div id="messages">
for m in messages:
<div class="msg-row" initial={{"opacity": 0, "y": 8}} animate={{"opacity": 1, "y": 0}}>
<Avatar fallback={m["author"][:2].upper()} size="sm" aria-hidden="true" />
<div class="msg"><b>{m["author"]}</b>{m["text"]}</div>
</div>
if not messages:
<p class="empty">No messages yet. Say hi!</p>
</div>
<form class="add" onsubmit={submit}>
<input id="author" class="pw-control name" bind={author} aria-label="Your name" />
<input id="draft" class="pw-control" bind={draft} placeholder="Message" aria-label="Message" />
<Button id="send" type="submit">Send</Button>
</form>
</CardContent>
</Card>
</main>
#What runs where
Output of pyweb inspect: every page variable, handler and server function, where it runs and why.
Output
page Lobby route=/
server rooms computed per request on the server; value sent because browser code reads it
page Room route=/chat/{room}
browser messages reactive state: assigned in received(); initial value computed on the server and sent
server feed computed per request on the server; value sent because browser code reads it
browser author reactive state: bound to an input (line 94); literal initial value
browser draft reactive state: bound to an input (line 95); literal initial value
browser received event handler (compiled to JavaScript)
browser on_mount event handler (compiled to JavaScript)
browser submit event handler (compiled to JavaScript)
rpc POST /__pyweb/rpc/history (room: str, after: int) -> list
rpc POST /__pyweb/rpc/send (room: str, author: str, text: str) -> None#Generated JavaScript
The browser modules the compiler wrote (before minification). They import the shared runtime.
JavaScript
// Lobby.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";
// display.pyweb
const { Badge } = (() => {
function Badge($p) {
const variant = $p["variant"] || (() => "soft");
const tone = $p["tone"] || (() => null);
const children = $p["children"] || (() => null);
const attrs = $p["$rest"] || (() => ({}));
return [$h("span", {"class": "pw-badge", "data-part": "badge", "data-variant": () => variant(), "data-tone": () => tone(), "$spread4": () => attrs()}, () => [$dyn(() => children())])];
}
return { Badge };
})();
const ROOMS = ["general", "python", "random"];
function Lobby($s) {
const rooms = $s["rooms"];
return [$h("main", null, () => [
$h("h1", null, () => [$t("Rooms")]),
$h("ul", {"class": "rooms"}, () => [$list(() => rooms, (room) => [$h("li", {"data-pw-motion": JSON.stringify({"animate": "fade-up"}), "style": ((i, s) => s)(null, null, null, "fade-up")}, () => [$h("a", {"class": "pw-card room", "href": $py.add("/chat/", $py.at(room, "name"))}, () => [
$h("b", null, () => [
$t("#"),
$t($py.text($py.at(room, "name")))
]),
Badge({"variant": () => "secondary", "children": () => [
$t($py.text($py.at(room, "count"))),
$t(" messages")
]})
])])])])
])];
}
$mount("Lobby", Lobby);
// Room.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";
import { subscribe as $subscribe, live as $live, join as $join } from "./live.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 };
})();
// card.pyweb
const { Card, 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 CardContent($p) {
const children = $p["children"] || (() => null);
const attrs = $p["$rest"] || (() => ({}));
return [$h("div", {"data-part": "content", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
}
return { Card, CardContent };
})();
// display.pyweb
const { Avatar } = (() => {
function Avatar($p) {
const src = $p["src"] || (() => null);
const alt = $p["alt"] || (() => "");
const fallback = $p["fallback"] || (() => "");
const size = $p["size"] || (() => "md");
const attrs = $p["$rest"] || (() => ({}));
const initials = $computed(() => $py.or(fallback(), () => $py.m($py.m("", "join", $py.iter($py.slice($py.m($py.str(alt()), "split"), null, 2, null)).map((w) => ($py.slice(w, null, 1, null)))), "upper")));
return [$h("span", {"class": "pw-avatar", "data-part": "avatar", "data-size": () => size(), "$spread3": () => attrs()}, () => [$when(() => $py.truth(src()), () => [$h("img", {"src": () => src(), "alt": () => alt(), "loading": "lazy"})], () => [$h("span", {"aria-label": () => $py.or(alt(), () => null), "role": () => ($py.truth(alt()) ? "img" : null)}, () => [$dyn(() => initials())])])])];
}
return { Avatar };
})();
const ROOMS = ["general", "python", "random"];
function Room($s) {
const room = $s["room"];
const messages = $signal("messages" in $s ? $s["messages"] : null, "messages");
const feed = $s["feed"];
const author = $signal("author" in $s ? $s["author"] : "guest", "author");
const draft = $signal("draft" in $s ? $s["draft"] : "", "draft");
function received(message) {
messages($py.add(messages(), [message]));
}
function on_mount() {
$subscribe(feed, received);
}
async function submit() {
if ($py.truth($py.m(draft(), "strip"))) {
(await $rpc("send", {"room": room, "author": author(), "text": draft()}));
draft("");
}
}
$onMount(on_mount);
return [$h("main", null, () => [
$h("p", null, () => [Button({"href": () => "/", "variant": () => "ghost", "size": () => "sm", "children": () => [$t("\u2190 Rooms")]})]),
$h("h1", null, () => [
$t("#"),
$t($py.text(room))
]),
Card({"children": () => [CardContent({"children": () => [
$h("div", {"id": "messages"}, () => [
$list(() => messages(), (m) => [$h("div", {"class": "msg-row", "data-pw-motion": JSON.stringify({"initial": {"opacity": 0, "y": 8}, "animate": {"opacity": 1, "y": 0}}), "style": ((i, s) => s)({"opacity": 0, "y": 8}, null, null, {"opacity": 1, "y": 0})}, () => [
Avatar({"fallback": () => $py.m($py.slice($py.at(m, "author"), null, 2, null), "upper"), "size": () => "sm", "$rest": () => ({"aria-hidden": "true"})}),
$h("div", {"class": "msg"}, () => [
$h("b", null, () => [$t($py.text($py.at(m, "author")))]),
$t($py.text($py.at(m, "text")))
])
])]),
$when(() => !$py.truth(messages()), () => [$h("p", {"class": "empty"}, () => [$t("No messages yet. Say hi!")])])
]),
$h("form", {"class": "add", "onsubmit": submit}, () => [
$h("input", {"id": "author", "class": "pw-control name", "$bind": author, "aria-label": "Your name"}),
$h("input", {"id": "draft", "class": "pw-control", "$bind": draft, "placeholder": "Message", "aria-label": "Message"}),
Button({"type": () => "submit", "children": () => [$t("Send")], "$rest": () => ({"id": "send"})})
])
]})]})
])];
}
$mount("Room", Room);