Routing (pyzed.routing)
Pages as folders of app/, like Next.js’ App Router: page.py, layout.py, template.py,
loading.py, error.py, not_found.py, [id], [...slug], [[...slug]] and (group).
See the Routing section.
pz.run(pz.RouterApp("app", title="Shop"))The router
Section titled “The router”RouterApp
Section titled “RouterApp”class RouterAppAn app whose window shows its routes:
pz.run(pz.RouterApp("app", title="Shop"))
class Shop(pz.RouterApp): # or subclass it routes = "app" title = "Shop" size = (1100, 720)The window’s title follows the page (its title or metadata, with the root layout’s
title_template); the app’s own title is used when the page has none. Alt+Left/Right,
the mouse’s back and forward buttons and Android’s back button move in the history.
on_navigate(location) runs after every navigation.
class Shop(pz.RouterApp):routes = "app"title = "Shop"Router
Section titled “Router”class RouterRoutes in folders, like Next.js’ App Router, or in a dict; see pyzed.routing.
routes is the app/ folder (a relative path is looked for next to the file that creates the
router, then in the current folder), or a dict such as {"/": home, "/users/[id]": user}.
initial is the first location and stale_time how many seconds the data of a page stays
fresh: after that, going to it again (not back or forward) loads it again. middleware is a
function (or a list) that runs before every navigation, before the middleware.py files of the
folders (see pz.middleware).
self.router = pz.Router("app")# in view(): return self.router.view()Links and hooks
Section titled “Links and hooks”link(href, content=None, *, replace=False, prefetch=True, router=None, size=None)A link to href (<Link> in Next.js): text in the accent color, or any widget, that navigates
when clicked.
href is a path ("/products/3"), relative to the current page ("../", "reviews"), a
query ("?page=2") or ("/users/[id]", {"id": 7}). replace replaces the history entry
instead of adding one; prefetch starts the page’s load when the mouse is over the link.
pz.link("/products/3", "See the monitor")nav_link
Section titled “nav_link”nav_link(href, label, *, icon=None, exact=None, router=None, description=None)A row for a sidebar or a menu (ui.list_item) that goes to href and shows as selected while
that page, or a page under it, is open (exact=True: only that page; the root / is exact).
pz.nav_link("/settings", "Settings", icon="settings")use_router
Section titled “use_router”use_router()The router drawing this view (useRouter()): use_router().push("/cart").
Outside a view (a callback, a form’s handler) it is the router that drew last.
pz.use_router().push("/cart")use_pathname
Section titled “use_pathname”use_pathname()The current path, like /products/3 (usePathname()).
use_params
Section titled “use_params”use_params()The parameters of the current page: {"id": "3"} for /products/[id] (useParams()).
use_search_params
Section titled “use_search_params”use_search_params()The current query as a dict, get_all(key) for repeated keys (useSearchParams()).
Inside pages
Section titled “Inside pages”not_found
Section titled “not_found”not_found()Stops drawing the page (or its load) and shows the closest not_found file, like Next.js’
notFound():
async def load(params): product = await shop.get(params["id"]) if product is None: pz.not_found() return productredirect
Section titled “redirect”redirect(href, *, push=False)Goes to href instead of the page being drawn (from a page, a layout or a load).
The current history entry is replaced, like Next.js’ redirect(); push=True adds one.
pz.redirect("/login")Location
Section titled “Location”@dataclassclass Location(pathname='/', search='', hash='')Where the router is: pathname (/products/3), the search query without ? and the
hash without #. The same parts as a browser’s URL, so a route maps to a web address as is.
SearchParams
Section titled “SearchParams”class SearchParamsThe query of the URL (?tab=reviews&tag=a&tag=b) as a dict of the first values.
get_all("tag") gives every value of a repeated key, str() the encoded query.
Middleware
Section titled “Middleware”middleware
Section titled “middleware”middleware(function=None, *, matcher=None)Marks a function as middleware for Router(middleware=[...]), with the addresses it runs for:
@pz.middleware(matcher="/admin/:path*")def admins_only(request): if not session.is_admin: return request.redirect("/")A plain function works too; matcher only narrows where it runs.
@pz.middleware(matcher="/admin/:path*")def admins_only(request): if not session.is_admin: return request.redirect("/")rewrite
Section titled “rewrite”rewrite(href)In middleware: keeps the address but shows the route at href (NextResponse.rewrite).
Return it, or raise it: return pz.rewrite("/maintenance").
return pz.rewrite("/maintenance")Request
Section titled “Request”@dataclassclass Request(location, previous, action, router, route=None, params={}, locals={})A navigation that middleware can let through, send elsewhere or stop.
location is where it goes (pathname, query, hash and href are its parts),
previous where the router is now (None at the start), action what started it ("start",
"push", "replace", "back", "forward" or "refresh"), route the pattern that
answers it ("/products/[id]", None when no page does) and params its values.
locals is a dict the pages, layouts and load functions of that location receive as locals.
Data and state
Section titled “Data and state”action
Section titled “action”action(function=None, *, refresh=True, invalidate=None, on_done=None, on_error=None)Makes function an :class:Action (see pyzed.actions): @pz.action or
@pz.action(refresh=False, invalidate="/products").
@pz.action(invalidate="/orders")async def place(item): await api.place(item)Action
Section titled “Action”class ActionA function that changes data, with its state: pending, result, error and calls.
Calling it starts the function and returns a concurrent.futures.Future; run(...)
calls it and waits (for tests and scripts). reset() clears result and error.
class StoreValues shared by the whole app (see pyzed.store).
Fields are annotated class attributes with their defaults; Cart(items=[...]) sets some.
subscribe(callback) calls callback(store) after each change, batch() groups several
changes into one, reset() goes back to the defaults and to_dict() gives the values.
Changing a list or dict in place (cart.items.append(x)) is seen by the next drawing; call
changed() after it so subscribers (and persist) hear about it too.
class Cart(pz.Store): items: list = []
cart = Cart()Notifications
Section titled “Notifications”notify
Section titled “notify”notify( title, body='', *, icon=None, image=None, actions=None, href=None, on_click=None, on_action=None, on_close=None, urgency='normal', sound=True, timeout=None, tag=None,)Shows a native desktop notification and returns it (see pyzed.notifications).
icon and image are paths or PNG bytes. actions are buttons, as {id: label} or a
list of labels; an id that starts with / (or ?) opens that page. href is the page a
click opens; on_click(notification), on_action(id) and on_close(reason) run on the UI
thread. urgency is "low", "normal" or "critical" (stays until answered),
sound True (the system’s), False or a sound’s name, and timeout the seconds on
screen (0: until dismissed; None: the system’s default). A new notification with the
tag of one still shown replaces it, like a download’s progress.
pz.notify("Order shipped", "On its way", href="/orders/3")DesktopNotification
Section titled “DesktopNotification”class DesktopNotificationA notification shown with pz.notify: close() takes it away, update(...) changes it.
native is False when it was shown without the system’s notifications (no buttons or
clicks then), closed once it left the screen and reason why: "expired",
"dismissed", "closed" or "unknown".