Example: Sales dashboard
Live queries, counters that count up, the kit's bar chart and a Chart.js chart from npm, updating in every open window.
- 128 lines of Python
- 1 page
- 2 server functions
- 3890 B page JS (gzip)
This example needs its server (database, sessions or server functions). Run it locally:
Terminal
pyweb dev examples/dashboard/app.pyweb#Source
examples/dashboard/app.pyweb
"""Sales dashboard: live queries, counters that count, the UI kit's chart and a Chart.js chart from npm.
Open it in two windows and record a sale: both update at once.
Set up with `pyweb add chart.js/auto` (already done here: see pyweb.lock).
"""
import random
from pyweb import App, live, npm, server
from pyweb.browser import watch
from pyweb.db import connect
from pyweb.ui import BarChart, Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Sparkline
Chart = npm("chart.js/auto")
app = App(title="Sales dashboard", stylesheets=["/static/app.css"])
db = connect("sqlite:///dashboard.db")
db.execute("create table if not exists sales (id integer primary key, product text, amount real)")
PRODUCTS = ["Lamp", "Desk", "Chair", "Shelf"]
if not db.execute("select count(*) from sales").fetchone()[0]:
with db.transaction():
for i in range(12):
db.execute("insert into sales (product, amount) values (?, ?)", (PRODUCTS[i % 4], 20 + i * 7))
@server
def record(product: str, amount: float) -> None:
if product not in PRODUCTS or not 0 < amount < 10_000:
return
db.execute("insert into sales (product, amount) values (?, ?)", (product, round(amount, 2)))
@server
def simulate() -> None:
"""Ten random sales in one transaction: pages get one update."""
with db.transaction():
for _ in range(10):
db.execute("insert into sales (product, amount) values (?, ?)",
(random.choice(PRODUCTS), round(random.uniform(10, 200), 2)))
@app.page("/")
def Dashboard():
totals = live(db, "select count(*) as n, coalesce(sum(amount), 0) as revenue from sales")
by_product = live(db, "select product, sum(amount) as revenue from sales group by product order by product")
recent = live(db, "select id, product, amount from sales order by id desc limit 6")
canvas = None
chart = None
product = "Lamp"
amount = "49"
def on_mount():
chart = Chart(canvas, {"type": "bar", "options": {"animation": False, "plugins": {"legend": {"display": False}}},
"data": {"labels": [r["product"] for r in by_product],
"datasets": [{"data": [r["revenue"] for r in by_product]}]}})
watch(lambda: by_product, redraw)
def redraw(rows):
chart.data.labels = [r["product"] for r in rows]
chart.data.datasets[0].data = [r["revenue"] for r in rows]
chart.update()
def add():
record(product, float(amount or 0))
<main>
<div class="head">
<h1>Sales</h1>
<Button id="simulate" variant="outline" onclick={lambda: simulate()}>Simulate 10 sales</Button>
</div>
<div class="kpis">
<Card>
<CardHeader><CardDescription>Sales</CardDescription></CardHeader>
<CardContent><b id="count" class="kpi" animate="count">{totals[0]["n"]}</b></CardContent>
</Card>
<Card>
<CardHeader><CardDescription>Revenue</CardDescription></CardHeader>
<CardContent>
<b id="revenue" class="kpi" animate="count">{f"${totals[0]['revenue']:,.2f}"}</b>
</CardContent>
</Card>
<Card>
<CardHeader><CardDescription>Latest amounts</CardDescription></CardHeader>
<CardContent>
<Sparkline values={[s["amount"] for s in reversed(recent)]} width={160} height={40} area={True}
label="Latest sale amounts" />
</CardContent>
</Card>
</div>
<div class="charts">
<Card>
<CardHeader>
<CardTitle>By product</CardTitle>
<CardDescription>The UI kit's chart: plain SVG, no JavaScript.</CardDescription>
</CardHeader>
<CardContent>
<BarChart data={by_product} x="product" y="revenue" height={180} label="Revenue by product" />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Chart.js</CardTitle>
<CardDescription>The same numbers through an npm package.</CardDescription>
</CardHeader>
<CardContent><canvas id="chart" ref={canvas} height="180"></canvas></CardContent>
</Card>
</div>
<Card>
<CardHeader><CardTitle>Record a sale</CardTitle></CardHeader>
<CardContent>
<form class="add" onsubmit={add}>
<select class="pw-control" bind={product} aria-label="Product">
for p in PRODUCTS:
<option value={p}>{p}</option>
</select>
<input class="pw-control" bind={amount} type="number" step="0.01" min="0" aria-label="Amount" />
<Button type="submit">Record sale</Button>
</form>
<h2>Latest</h2>
<ul id="recent">
for s in recent:
<li initial={{"opacity": 0, "y": -6}} animate={{"opacity": 1, "y": 0}}>
<span>{s["product"]}</span><span class="muted">{f"${s['amount']:.2f}"}</span>
</li>
</ul>
</CardContent>
</Card>
</main>
#What runs where
Output of pyweb inspect: every page variable, handler and server function, where it runs and why.
Output
page Dashboard route=/
browser totals reactive state: a live query: the server sends new rows when its tables change; initial value computed on the server and sent
browser by_product reactive state: a live query: the server sends new rows when its tables change; initial value computed on the server and sent
browser recent reactive state: a live query: the server sends new rows when its tables change; initial value computed on the server and sent
browser canvas reactive state: set to an element by ref= (line 105); literal initial value
browser chart reactive state: assigned in on_mount(); literal initial value
browser product reactive state: bound to an input (line 112); literal initial value
browser amount reactive state: bound to an input (line 116); literal initial value
browser on_mount event handler (compiled to JavaScript)
browser redraw event handler (compiled to JavaScript)
browser add event handler (compiled to JavaScript)
rpc POST /__pyweb/rpc/record (product: str, amount: float) -> None
rpc POST /__pyweb/rpc/simulate () -> None#Generated JavaScript
The browser modules the compiler wrote (before minification). They import the shared runtime.
JavaScript
// Dashboard.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";
import $npm_chart_js_auto_default_336847 from "chart.js/auto";
// 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, CardHeader, CardDescription, CardContent, CardTitle } = (() => {
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())])];
}
function CardTitle($p) {
const children = $p["children"] || (() => null);
const attrs = $p["$rest"] || (() => ({}));
return [$h("h3", {"data-part": "title", "$spread1": () => attrs()}, () => [$dyn(() => children())])];
}
return { Card, CardHeader, CardDescription, CardContent, CardTitle };
})();
// chart.pyweb
const { Sparkline, BarChart } = (() => {
function _keys(y) {
return ($py.isinstance(y, ["str"]) ? [y] : $py.list(y));
}
function _num(v) {
return (($py.isinstance(v, ["int", "float"]) && !$py.isinstance(v, ["bool"])) ? v : 0);
}
function _nice(top) {
let m, mag;
if ((top <= 0)) {
return 1;
}
mag = (10 ** Math.floor(Math.log10(top)));
for (m of $py.iter([1, 2, 2.5, 5, 10])) {
if ((top <= $py.mul(m, mag))) {
return $py.mul(m, mag);
}
}
return $py.mul(10, mag);
}
function _top(rows, keys, stacked) {
let best, k, r;
best = 0;
for (r of $py.iter(rows)) {
if ($py.truth(stacked)) {
best = $py.max(best, $py.sum($py.iter(keys).map((k) => ($py.max(0, _num($py.m(r, "get", k)))))));
} else {
for (k of $py.iter(keys)) {
best = $py.max(best, _num($py.m(r, "get", k)));
}
}
}
return _nice(best);
}
function _n(x) {
let r;
r = $py.round(x, 2);
return ($py.eq(r, $py.int(r)) ? $py.str($py.int(r)) : $py.str(r));
}
function _pct(x) {
return $py.add(_n(x), "%");
}
function _label(v, fmt) {
return ($py.truth(fmt) ? $py.str(fmt(v)) : _n(v));
}
function _ticks(top, fmt, count = 4) {
return $py.iter($py.range($py.add(count, 1))).map((i) => ({"pos": _n((100 - $py.div($py.mul(i, 100), count))), "y": _pct((100 - $py.div($py.mul(i, 100), count))), "text": _label($py.div($py.mul(top, i), count), fmt)}));
}
function _color(i, colors) {
if ($py.truth(colors)) {
return $py.at(colors, $py.mod(i, $py.len(colors)));
}
return $py.add($py.add("var(--pw-chart-", $py.str($py.add($py.mod(i, 5), 1))), ")");
}
function _bars(rows, x, keys, top, stacked, colors, fmt) {
let band, base, h, i, j, left, n, out, r, v, width, y;
n = $py.max(1, $py.len(rows));
band = $py.div(100, n);
width = ($py.truth(stacked) ? $py.mul(band, 0.7) : $py.div($py.mul(band, 0.7), $py.len(keys)));
out = [];
for (i of $py.iter($py.range($py.len(rows)))) {
r = $py.at(rows, i);
base = 0;
for (j of $py.iter($py.range($py.len(keys)))) {
v = $py.max(0, _num($py.m(r, "get", $py.at(keys, j))));
h = $py.mul($py.div(v, top), 100);
left = $py.add($py.add($py.mul(i, band), $py.mul(band, 0.15)), ($py.truth(stacked) ? 0 : $py.mul(j, width)));
y = ((100 - base) - h);
$py.m(out, "append", {"x": _n(left), "y": _n(y), "w": _n(width), "h": _n(h), "color": _color(j, colors), "title": $py.add($py.add($py.add($py.add($py.str($py.m(r, "get", x, "")), " \u00b7 "), $py.str($py.at(keys, j))), ": "), _label(v, fmt))});
if ($py.truth(stacked)) {
base = $py.add(base, h);
}
}
}
return out;
}
function _x_labels(rows, x, edge) {
let every, i, n, out, pos;
n = $py.len(rows);
every = $py.max(1, Math.ceil((n / 10)));
out = [];
for (i of $py.iter($py.range(n))) {
if (($py.mod(i, every) === 0)) {
pos = ($py.truth(edge) ? ((n > 1) ? $py.mul($py.div(i, (n - 1)), 100) : 50) : $py.div($py.mul($py.add(i, 0.5), 100), n));
$py.m(out, "append", {"x": _pct(pos), "text": $py.str($py.m($py.at(rows, i), "get", x, ""))});
}
}
return out;
}
function Sparkline($p) {
const values = $p["values"] || (() => null);
const width = $p["width"] || (() => 120);
const height = $p["height"] || (() => 32);
const area = $p["area"] || (() => false);
const color = $p["color"] || (() => null);
const label = $p["label"] || (() => null);
const attrs = $p["$rest"] || (() => ({}));
const vals = $computed(() => $py.iter($py.or(values(), () => [])).map((v) => (_num(v))));
const lo = $computed(() => ($py.truth(vals()) ? $py.min(vals()) : 0));
const hi = $computed(() => ($py.truth(vals()) ? $py.max(vals()) : 1));
const span = $computed(() => $py.or((hi() - lo()), () => 1));
const n = $computed(() => $py.len(vals()));
const d = $computed(() => $py.m(" ", "join", $py.iter($py.range(n())).map((i) => ($py.add($py.add($py.add(((i === 0) ? "M" : "L"), _n(((n() > 1) ? $py.mul($py.div(i, (n() - 1)), 100) : 50))), " "), _n((92 - $py.mul($py.div(($py.at(vals(), i) - lo()), span()), 84))))))));
return [$h("svg", {"class": "pw-sparkline", "data-part": "sparkline", "width": () => width(), "height": () => height(), "viewBox": "0 0 100 100", "preserveAspectRatio": "none", "role": "img", "aria-label": () => $py.or(label(), () => $py.add("Trend: ", $py.m(", ", "join", $py.iter(vals()).map((v) => (_n(v)))))), "style": () => ($py.truth(color()) ? {"color": color()} : null), "$spread9": () => attrs()}, () => [
$when(() => ($py.truth(area()) && (n() > 1)), () => [$h("path", {"data-part": "area", "d": () => $py.add(d(), " L100 100 L0 100 Z")})]),
$h("path", {"data-part": "line", "d": () => d()})
])];
}
function BarChart($p) {
const data = $p["data"] || (() => null);
const x = $p["x"] || (() => "x");
const y = $p["y"] || (() => "y");
const height = $p["height"] || (() => 240);
const stacked = $p["stacked"] || (() => false);
const colors = $p["colors"] || (() => null);
const label = $p["label"] || (() => null);
const format = $p["format"] || (() => null);
const legend = $p["legend"] || (() => null);
const attrs = $p["$rest"] || (() => ({}));
const rows = $computed(() => $py.list($py.or(data(), () => [])));
const keys = $computed(() => _keys(y()));
const top = $computed(() => _top(rows(), keys(), stacked()));
const show_legend = $computed(() => ((legend() == null) ? ($py.len(keys()) > 1) : legend()));
return [$h("figure", {"class": "pw-chart", "data-part": "chart", "data-kind": "bar", "style": () => ({"--pw-chart-height": $py.add($py.str(height()), "px")}), "$spread4": () => attrs()}, () => [
$h("div", {"data-part": "plot"}, () => [
$h("div", {"data-part": "y-axis", "aria-hidden": "true"}, () => [$list(() => _ticks(top(), format()), (t) => [$h("span", {"style": {"top": $py.at(t, "y")}}, () => [$t($py.text($py.at(t, "text")))])])]),
$h("svg", {"viewBox": "0 0 100 100", "preserveAspectRatio": "none", "role": "img", "aria-label": () => $py.or(label(), () => "Bar chart")}, () => [
$list(() => _ticks(top(), format()), (t) => [$h("line", {"data-part": "grid", "x1": "0", "x2": "100", "y1": $py.at(t, "pos"), "y2": $py.at(t, "pos")})]),
$list(() => _bars(rows(), x(), keys(), top(), stacked(), colors(), format()), (b) => [$h("rect", {"data-part": "bar", "x": $py.at(b, "x"), "y": $py.at(b, "y"), "width": $py.at(b, "w"), "height": $py.at(b, "h"), "fill": $py.at(b, "color")}, () => [$h("title", null, () => [$t($py.text($py.at(b, "title")))])])])
]),
$h("div", {"data-part": "x-axis", "aria-hidden": "true"}, () => [$list(() => _x_labels(rows(), x(), false), (t) => [$h("span", {"style": {"left": $py.at(t, "x")}}, () => [$t($py.text($py.at(t, "text")))])])])
]),
$when(() => $py.truth(show_legend()), () => [$h("ul", {"class": "pw-chart-legend", "data-part": "legend"}, () => [$list(() => $py.range($py.len(keys())), (i) => [$h("li", null, () => [
$h("span", {"data-part": "swatch", "style": () => ({"background": _color(i, colors())})}),
$dyn(() => $py.at(keys(), i))
])])])]),
$h("table", {"class": "pw-sr-only"}, () => [
$h("caption", null, () => [$dyn(() => $py.or(label(), () => "Bar chart"))]),
$h("thead", null, () => [$h("tr", null, () => [
$h("th", {"scope": "col"}, () => [$dyn(() => x())]),
$list(() => keys(), (k) => [$h("th", {"scope": "col"}, () => [$t($py.text(k))])])
])]),
$h("tbody", null, () => [$list(() => rows(), (r) => [$h("tr", null, () => [
$h("th", {"scope": "row"}, () => [$dyn(() => $py.m(r, "get", x(), ""))]),
$list(() => keys(), (k) => [$h("td", null, () => [$dyn(() => _label(_num($py.m(r, "get", k)), format()))])])
])])])
])
])];
}
return { Sparkline, BarChart };
})();
const PRODUCTS = ["Lamp", "Desk", "Chair", "Shelf"];
function Dashboard($s) {
const totals = $signal("totals" in $s ? $s["totals"] : null, "totals");
const by_product = $signal("by_product" in $s ? $s["by_product"] : null, "by_product");
const recent = $signal("recent" in $s ? $s["recent"] : null, "recent");
const canvas = $signal("canvas" in $s ? $s["canvas"] : null, "canvas");
const chart = $signal("chart" in $s ? $s["chart"] : null, "chart");
const product = $signal("product" in $s ? $s["product"] : "Lamp", "product");
const amount = $signal("amount" in $s ? $s["amount"] : "49", "amount");
function on_mount() {
chart($py.call($npm_chart_js_auto_default_336847, [canvas(), {"type": "bar", "options": {"animation": false, "plugins": {"legend": {"display": false}}}, "data": {"labels": $py.iter(by_product()).map((r) => ($py.at(r, "product"))), "datasets": [{"data": $py.iter(by_product()).map((r) => ($py.at(r, "revenue")))}]}}]));
$py.watch((() => (by_product())), redraw);
}
function redraw(rows) {
$py.setp(chart, ["data", "labels"], $py.iter(rows).map((r) => ($py.at(r, "product"))));
$py.setp(chart, ["data", "datasets", 0, "data"], $py.iter(rows).map((r) => ($py.at(r, "revenue"))));
$py.mut(chart, [], ($v) => $py.m($v, "update"));
}
async function add() {
(await $rpc("record", {"product": product(), "amount": $py.float($py.or(amount(), () => 0))}));
}
$live(totals, $s["$live:totals"]);
$live(by_product, $s["$live:by_product"]);
$live(recent, $s["$live:recent"]);
$onMount(on_mount);
return [$h("main", null, () => [
$h("div", {"class": "head"}, () => [
$h("h1", null, () => [$t("Sales")]),
Button({"variant": () => "outline", "onclick": () => (async () => ((await $rpc("simulate", {})))), "children": () => [$t("Simulate 10 sales")], "$rest": () => ({"id": "simulate"})})
]),
$h("div", {"class": "kpis"}, () => [
Card({"children": () => [
CardHeader({"children": () => [CardDescription({"children": () => [$t("Sales")]})]}),
CardContent({"children": () => [$h("b", {"id": "count", "class": "kpi", "data-pw-motion": JSON.stringify({"animate": "count"}), "style": ((i, s) => s)(null, null, null, "count")}, () => [$dyn(() => $py.at($py.at(totals(), 0), "n"))])]})
]}),
Card({"children": () => [
CardHeader({"children": () => [CardDescription({"children": () => [$t("Revenue")]})]}),
CardContent({"children": () => [$h("b", {"id": "revenue", "class": "kpi", "data-pw-motion": JSON.stringify({"animate": "count"}), "style": ((i, s) => s)(null, null, null, "count")}, () => [$dyn(() => `$${$py.format($py.at($py.at(totals(), 0), "revenue"), ",.2f")}`)])]})
]}),
Card({"children": () => [
CardHeader({"children": () => [CardDescription({"children": () => [$t("Latest amounts")]})]}),
CardContent({"children": () => [Sparkline({"values": () => $py.iter($py.reversed(recent())).map((s) => ($py.at(s, "amount"))), "width": () => 160, "height": () => 40, "area": () => true, "label": () => "Latest sale amounts"})]})
]})
]),
$h("div", {"class": "charts"}, () => [
Card({"children": () => [
CardHeader({"children": () => [
CardTitle({"children": () => [$t("By product")]}),
CardDescription({"children": () => [$t("The UI kit's chart: plain SVG, no JavaScript.")]})
]}),
CardContent({"children": () => [BarChart({"data": () => by_product(), "x": () => "product", "y": () => "revenue", "height": () => 180, "label": () => "Revenue by product"})]})
]}),
Card({"children": () => [
CardHeader({"children": () => [
CardTitle({"children": () => [$t("Chart.js")]}),
CardDescription({"children": () => [$t("The same numbers through an npm package.")]})
]}),
CardContent({"children": () => [$h("canvas", {"id": "chart", "$ref": canvas, "height": "180"})]})
]})
]),
Card({"children": () => [
CardHeader({"children": () => [CardTitle({"children": () => [$t("Record a sale")]})]}),
CardContent({"children": () => [
$h("form", {"class": "add", "onsubmit": add}, () => [
$h("select", {"class": "pw-control", "$bind": product, "aria-label": "Product"}, () => [$list(() => PRODUCTS, (p) => [$h("option", {"value": p}, () => [$t($py.text(p))])])]),
$h("input", {"class": "pw-control", "$bind": amount, "type": "number", "step": "0.01", "min": "0", "aria-label": "Amount"}),
Button({"type": () => "submit", "children": () => [$t("Record sale")]})
]),
$h("h2", null, () => [$t("Latest")]),
$h("ul", {"id": "recent"}, () => [$list(() => recent(), (s) => [$h("li", {"data-pw-motion": JSON.stringify({"initial": {"opacity": 0, "y": (-6)}, "animate": {"opacity": 1, "y": 0}}), "style": ((i, s) => s)({"opacity": 0, "y": (-6)}, null, null, {"opacity": 1, "y": 0})}, () => [
$h("span", null, () => [$t($py.text($py.at(s, "product")))]),
$h("span", {"class": "muted"}, () => [$t($py.text(`$${$py.format($py.at(s, "amount"), ".2f")}`))])
])])])
]})
]})
])];
}
$mount("Dashboard", Dashboard);