Skip to content

Router

wybthon.router

router

Routing and the data layer, as in Solid Router 2.0.

Import it from wybthon.router:

from wybthon import FormData, component, create_memo, html, server_function
from wybthon.router import Route, create_router, form_action, query


@query
@server_function
async def get_user(user_id: int) -> User:
    return await db.users.get(user_id)


@form_action
@server_function
async def rename(user_id: int, form: FormData) -> None:
    await db.users.rename(user_id, form["name"])


@component
def Profile(params: dict[str, str]):
    user = create_memo(lambda: get_user(int(params["id"])))
    return html(t'''
      <h1>{user().name}</h1>
      <form action={rename.bind(user().id)} method="post">
        <input name="name"><button>Rename</button>
      </form>
    ''')


router = create_router([Route("/", Home), Route("/users/:id", Profile), Route("*404", NotFound)])

Path matching (match_route) needs no browser, so it also runs in tests, tools, and on the server.

Classes:

Name Description
Query

A deduplicated, revalidating read; returned by query.

ApiRoute

A route module's HTTP handlers (server side).

FormAction

An action a form can post to; returned by form_action.

Submission

A settled submission of a form action; see use_submissions.

Location

The current URL, read reactively; returned by use_location.

SearchParams

A decoded query string: each name's last value, plus get_all.

RouteSpec

A route without a component, for matching in tests and tools.

LinkState

Whether a link's target is the current page; returned by use_link_state.

Params

The matched route's path parameters, read with params["id"]; every read is tracked.

PreloadArgs

What a route's preload function receives.

Route

A route: a path pattern, the component it shows, and nested routes.

Router

A route tree; returned by create_router.

SearchParamsView

The query string's parameters, read with search["page"]; every read is tracked.

Functions:

Name Description
query

Wrap an async read so calls are deduplicated and can be revalidated by key.

revalidate

Refetch the queries whose keys start with keys (every query when omitted).

api_routes

The HTTP handlers the routes package defines, with their path patterns.

file_routes

The route tree for a package of route modules (see the module docs for the layout).

form_action

Make an async function something a <form> can post to.

use_submissions

The settled submissions of action, oldest first, as a tracked accessor.

navigate

Go to path within the app, or load it when it's on another origin.

use_location

The current URL; read location.path, .search, .hash, or .query reactively.

match_route

The best matching route for pathname, with its parameters and its chain of parents.

Outlet

The matched child route, inside a layout route's component (the same as its children prop).

create_router

Create the app's router from its route tree, as Solid Router 2.0's createRouter does.

preload_route

Preload the code and data of the route href shows; returns an awaitable, or None.

use_link_state

Whether a link to href is active or current, for styling navigation.

use_params

The matched route's path parameters: use_params()["id"], tracked (empty outside a router).

use_route_matches

Tracked accessor for the routes the URL shows, root to leaf.

use_search_params

The query string's parameters, and a function that updates them.

Attributes:

Name Type Description
url Accessor[str]

Tracked accessor for the current path, query, and hash (the request URL on the server).

url module-attribute

url: Accessor[str] = _Url()

Tracked accessor for the current path, query, and hash (the request URL on the server).

Query

Query(fn: Callable[P, Awaitable[R]], key: str)

A deduplicated, revalidating read; returned by query.

Call it like the function it wraps; the call returns a coroutine for the result. Read it in an async memo (create_memo(lambda: get_user(props.params["id"]))) and the memo loads under the nearest Loading boundary, refetches when revalidate names its key, and holds the old value on screen while it does.

Attributes:

Name Type Description
key

The key revalidate matches. A call's full key is this key followed by its arguments.

Methods:

Name Description
key_for

The full key of a call with these arguments.

key_for

key_for(*args: P.args, **kwargs: P.kwargs) -> str

The full key of a call with these arguments.

ApiRoute dataclass

ApiRoute(path: str, methods: frozenset[str], package: str, relative: tuple[str, ...])

A route module's HTTP handlers (server side).

Attributes:

Name Type Description
path str

The route's path pattern.

methods frozenset[str]

The HTTP methods it handles.

package str

The routes package.

relative tuple[str, ...]

The module's path under the package, without .py.

Methods:

Name Description
handler

The module's handler for method, imported on first use.

handler

handler(method: str) -> Any

The module's handler for method, imported on first use.

FormAction

FormAction(fn: Callable[..., Awaitable[R]], name: str, *, parent: Any = None, bound: tuple[Any, ...] = ())

An action a form can post to; returned by form_action.

Use it as a form's (or a submit button's formaction) attribute, or call it directly with the same arguments as the function it wraps.

Attributes:

Name Type Description
name

The action's stable name (a server function's id).

pending Accessor[bool]

Tracked accessor: True while a submission is in flight.

Methods:

Name Description
bind

This action with args passed ahead of the form data (Solid's action.with).

on_submit

Call fn(*input) when a submission starts, inside its transaction.

on_settled

Call fn(submission) when a submission settles (owner-scoped, like on_submit).

url property

url: str

What the form's action attribute holds: the URL a JavaScript-free post goes to.

bind

bind(*args: Any) -> FormAction[..., R]

This action with args passed ahead of the form data (Solid's action.with).

on_submit

on_submit(fn: Callable[..., Any]) -> FormAction[P, R]

Call fn(*input) when a submission starts, inside its transaction.

Write optimistic state here: it reverts when the submission settles. The hook belongs to the calling owner and is removed when that owner is disposed.

on_settled

on_settled(fn: Callable[[Submission], Any]) -> FormAction[P, R]

Call fn(submission) when a submission settles (owner-scoped, like on_submit).

Submission dataclass

Submission(input: list[Any], result: Any = None, error: BaseException | None = None, url: str = '', _action: FormAction[..., Any] | None = None)

A settled submission of a form action; see use_submissions.

Attributes:

Name Type Description
input list[Any]

The arguments the action received: bound arguments, then the FormData.

result Any

What the action returned, when it succeeded.

error BaseException | None

The exception it raised, when it failed.

url str

The URL the form posted to.

Methods:

Name Description
clear

Remove this submission from its action's history.

retry

Submit the same input again; returns the call's future.

clear

clear() -> None

Remove this submission from its action's history.

retry

retry() -> Any

Submit the same input again; returns the call's future.

Location

The current URL, read reactively; returned by use_location.

Every property is a tracked read, so a binding or memo that reads one updates when the URL changes.

Attributes:

Name Type Description
path str

The path, such as /users/42.

search str

The query string, with its leading ? (or "").

hash str

The decoded fragment, without its leading #.

query SearchParams

The parsed query string.

href str

Path, query, and hash together.

path property

path: str

The path, such as /users/42.

search property

search: str

The query string, with its leading ? (or "").

hash property

hash: str

The decoded fragment, without its leading #.

query property

query: SearchParams

The parsed query string.

href property

href: str

Path, query, and hash together.

SearchParams

SearchParams(search: str = '')

Bases: dict[str, str]

A decoded query string: each name's last value, plus get_all.

Methods:

Name Description
get_all

Every value of key, in URL order.

merged

The query string with changes applied (None or "" removes a key).

get_all

get_all(key: str) -> list[str]

Every value of key, in URL order.

merged

merged(changes: dict[str, Any]) -> str

The query string with changes applied (None or "" removes a key).

RouteSpec dataclass

RouteSpec(path: str, children: list[RouteSpec] | None = None)

A route without a component, for matching in tests and tools.

Attributes:

Name Type Description
path str

Route pattern (for example "/users/:id").

children list[RouteSpec] | None

Nested routes, whose paths continue this one's.

LinkState dataclass

LinkState(active: Accessor[bool], current: Accessor[bool])

Whether a link's target is the current page; returned by use_link_state.

Attributes:

Name Type Description
active Accessor[bool]

Tracked accessor: the current path is the link's path, or (unless end) below it. The base path only matches exactly.

current Accessor[bool]

Tracked accessor: same path and same query, ignoring the hash and parameter order (what aria-current="page" means).

Params

Params(source: Accessor[dict[str, str]])

Bases: Mapping[str, str]

The matched route's path parameters, read with params["id"]; every read is tracked.

What use_params returns, as Solid's useParams() returns a reactive object: a read inside markup, a memo, or an effect updates when the URL's parameters change.

PreloadArgs dataclass

PreloadArgs(params: dict[str, str], location: str, intent: Literal['initial', 'navigate', 'preload'])

What a route's preload function receives.

Attributes:

Name Type Description
params dict[str, str]

The matched path parameters.

location str

The URL being preloaded (path, query, and hash).

intent Literal['initial', 'navigate', 'preload']

"initial" (the first render, on the server or while hydrating), "navigate" (the router is going there), or "preload" (a link the pointer rests on, or preload_route).

Route dataclass

Route(path: str = '', component: Any = None, children: list[Route] = list(), preload: Callable[[PreloadArgs], Any] | None = None)

A route: a path pattern, the component it shows, and nested routes.

Patterns are literals, :name parameters, optional :name? parameters, and a final *name catch-all ("*404" matches anything). A child's path continues its parent's, and a route with children is a layout: it renders when one of its children matches, with that child as its children prop (and as Outlet()). A route with no component renders its children directly.

Attributes:

Name Type Description
path str

The path pattern.

component Any

The component to show. It receives whichever of the route props it declares as parameters: params (the matched path parameters, a dict[str, str]), search (the parsed query string, a SearchParams), data (what preload returned, resolved), and children (the matched child route, for a layout). Navigating between URLs the same route matches updates them in place instead of remounting.

children list[Route]

Nested routes.

preload Callable[[PreloadArgs], Any] | None

Called with PreloadArgs when the route is about to show, or when a link to it is preloaded. Warm the route's queries here. Its result, once any awaitable it returns resolves, is the component's data.

Router

Router(routes: list[Route], base: str, preload_links: bool)

A route tree; returned by create_router.

Call it to render: router(), or router(root=Shell) with a root layout component that stays mounted and receives the matched route as its children.

Attributes:

Name Type Description
routes

The route tree.

base

The base path the router matches under.

Methods:

Name Description
match

The routes href shows, root to leaf ([] when nothing matches); no rendering involved.

match

match(href: str) -> list[Route]

The routes href shows, root to leaf ([] when nothing matches); no rendering involved.

SearchParamsView

SearchParamsView(source: Accessor[SearchParams])

Bases: Mapping[str, str]

The query string's parameters, read with search["page"]; every read is tracked.

The first half of what use_search_params returns. get_all(name) reads every value of a repeated parameter.

Methods:

Name Description
get_all

Every value of key, in URL order (tracked).

get_all

get_all(key: str) -> list[str]

Every value of key, in URL order (tracked).

query

query(fn: Callable[P, Awaitable[R]], key: str | None = None) -> Query[P, R]
query(key: str) -> Callable[[Callable[P, Awaitable[R]]], Query[P, R]]
query(fn: Any, key: str | None = None) -> Any

Wrap an async read so calls are deduplicated and can be revalidated by key.

Use it as a decorator, bare or with a key, or call it with a function and a key, as in Solid:

@query
@server_function
async def get_user(user_id: int) -> User:
    return await db.users.get(user_id)


@component
def Profile(params: dict[str, str]):
    user = create_memo(lambda: get_user(int(params["id"])))
    return html(t"<h1>{user().name}</h1>")

A query:

  1. dedupes calls on the server for the lifetime of the request;
  2. in the browser, reuses a result for five seconds after it arrives, so a link's preload and the page it opens share one fetch;
  3. refetches, in every memo that read it, when revalidate names its key, or when a mutation completes (see server_function).

A server function wrapped in a query is called with GET.

Parameters:

Name Type Description Default
fn Any

The async function to wrap (or, used as @query("key"), the key).

required
key str | None

The query's key. Defaults to the server function's id, or the function's module and qualified name.

None

revalidate

revalidate(keys: str | Query[..., Any] | Iterable[str | Query[..., Any]] | None = None) -> None

Refetch the queries whose keys start with keys (every query when omitted).

Each memo that read a matching query runs again; a memo with a value holds it on screen until the new one lands. On the server it does nothing.

Parameters:

Name Type Description Default
keys str | Query[..., Any] | Iterable[str | Query[..., Any]] | None

A key, a Query, or several. A key matches every call whose full key starts with it, so revalidate(get_user) refetches every user.

None

api_routes

api_routes(package: str = 'app.routes') -> list[ApiRoute]

The HTTP handlers the routes package defines, with their path patterns.

file_routes

file_routes(package: str = 'app.routes') -> list[Route]

The route tree for a package of route modules (see the module docs for the layout).

Parameters:

Name Type Description Default
package str

The dotted name of the routes package.

'app.routes'

Returns:

Type Description
list[Route]

Routes for create_router.

form_action

form_action(fn: Callable[P, Awaitable[R]], name: str | None = None) -> FormAction[P, R]

Make an async function something a <form> can post to.

Usually it wraps a server function, which makes the form work before Python has booted. A client-only action (a plain async def) needs a stable name, since its URL must be the same on the server and in the browser.

Parameters:

Name Type Description Default
fn Callable[P, Awaitable[R]]

The async function; it receives any bound arguments, then the form's FormData.

required
name str | None

The action's name; defaults to the server function's id.

None

Returns:

Type Description
FormAction[P, R]

use_submissions

use_submissions(action: FormAction[..., Any], where: Callable[[list[Any]], bool] | None = None) -> Accessor[list[Submission]]

The settled submissions of action, oldest first, as a tracked accessor.

This is history, not in-flight state: use action.pending() and optimistic primitives for what a submission shows while it runs. On the page a JavaScript-free post returns to, it includes that post's submission.

Parameters:

Name Type Description Default
action FormAction[..., Any]

The form action.

required
where Callable[[list[Any]], bool] | None

Optional filter on each submission's input.

None

navigate

navigate(path: str, *, replace: bool = False, scroll: bool = True) -> None

Go to path within the app, or load it when it's on another origin.

Relative paths resolve against the current URL. Back and forward restore scroll positions; an ordinary navigation scrolls to the hash's target, or to the top, once the destination is on screen. A path starting with / is a full path: the router's base isn't added. A no-op while rendering on the server.

use_location

use_location() -> Location

The current URL; read location.path, .search, .hash, or .query reactively.

match_route

match_route(routes: list[Any], pathname: str, base_path: str = '') -> tuple[Any, dict[str, Any]] | None

The best matching route for pathname, with its parameters and its chain of parents.

Parameters:

Name Type Description Default
routes list[Any]

Route definitions: anything with a path and optional children (Route, RouteSpec).

required
pathname str

A URL path (a query or hash is ignored).

required
base_path str

The router's base path, stripped before matching.

''

Returns:

Type Description
tuple[Any, dict[str, Any]] | None

(route, {"params": ..., "matches": [root, ..., route]}), or

tuple[Any, dict[str, Any]] | None

None when nothing matches.

Outlet

Outlet() -> VNode

The matched child route, inside a layout route's component (the same as its children prop).

create_router

create_router(routes: list[Route], *, base: str = '', preload_links: bool = True) -> Router

Create the app's router from its route tree, as Solid Router 2.0's createRouter does.

The router follows plain <a href> links: a click on a same-origin link under the base path navigates with the History API instead of loading a page. Clicks with a modifier key, links with a target, download, or rel="external", and other origins are left to the browser. With preload_links, resting the pointer on a link (or focusing it) preloads its route's code and data.

router = create_router([
    Route("/", Home),
    Route("/users/:id", User, preload=lambda args: get_user(int(args.params["id"]))),
    Route("*404", NotFound),
])

def app():
    return router(root=Shell)

Parameters:

Name Type Description Default
routes list[Route]

The route tree (see Route), or file_routes().

required
base str

The base path the app is served under. Links and navigate take full paths, as everywhere in HTML.

''
preload_links bool

Preload a link's route when the pointer rests on it.

True

Returns:

Type Description
Router

A Router; call it to render.

preload_route

preload_route(href: str) -> Any

Preload the code and data of the route href shows; returns an awaitable, or None.

use_link_state(href: str | Callable[[], str], *, end: bool = False) -> LinkState

Whether a link to href is active or current, for styling navigation.

@component
def NavLink(props: NavLinkProps):
    state = use_link_state(lambda: props.href)
    return html(t'<a href={props.href} class={"active" if state.active() else ""}
                   aria-current={"page" if state.current() else None}>{props.children}</a>')

use_params

use_params() -> Params

The matched route's path parameters: use_params()["id"], tracked (empty outside a router).

use_route_matches

use_route_matches() -> Accessor[list[Route]]

Tracked accessor for the routes the URL shows, root to leaf.

use_search_params

use_search_params() -> tuple[SearchParamsView, Callable[..., None]]

The query string's parameters, and a function that updates them.

Reads of the first half are tracked. The setter merges its changes into the current query (None or "" removes a key) and navigates without scrolling:

search, set_search = use_search_params()
set_search(page=int(search.get("page", "1")) + 1)

What's in this module

Routing and the data layer, as in Solid Router 2.0. Import it from wybthon.router; these names aren't re-exported from wybthon. A route's component declares the route props it needs (params, search, data, and children) as parameters, and the router passes only those. Only a change in which route matches remounts a route; param and search changes flow into the mounted component as prop updates.

Name Description
create_router create_router(routes, *, base="", preload_links=True): the app's Router. Call it to render: router(), or router(root=Shell) with a root layout.
Route Route(path, component=None, children=[], preload=None). Patterns: :id, :id?, and a final *name catch-all.
PreloadArgs What a route's preload receives: params, location, and intent.
Outlet The matched child route, inside a layout.
file_routes file_routes("app.routes"): a route tree from a package of route modules.
navigate navigate(path, *, replace=False, scroll=True).
use_params Tracked accessor for the path parameters.
use_search_params (search, set_search): the SearchParams and a merging setter.
use_location The URL: .path, .search, .hash, .query, .href, each a tracked read. url is the raw accessor.
use_route_matches Tracked accessor for the matched routes, root to leaf.
use_link_state use_link_state(href, *, end=False): .active() and .current() accessors for styling links.
preload_route Preload a route's code and data from code.
query, revalidate Deduplicated, revalidating reads.
form_action, use_submissions Actions a form posts to, and their settled submissions.
match_route, RouteSpec Matching without a browser.

Links are plain <a href> elements: the router follows same-origin clicks under its base path and leaves modifier-key clicks, target, download, rel="external", and other origins to the browser.

from wybthon import Children, component, html
from wybthon.router import Route, SearchParams, create_router, use_link_state


@component
def Home():
    return html(t"<h1>Home</h1>")


@component
def User(params: dict[str, str], search: SearchParams):
    return html(t"<h1>User {params['id']} (tab={search.get('tab', 'info')})</h1>")


@component
def NotFound():
    return html(t"<h1>Not found</h1>")


@component
def Shell(children: Children = None):
    users = use_link_state("/users")
    return html(t"""
      <nav><a href="/">Home</a> <a href="/users/1?tab=posts" class={"active" if users.active() else ""}>Ada</a></nav>
      {children}
    """)


router = create_router([Route("/", Home), Route("/users/:id", User), Route("*404", NotFound)])


def app():
    return router(root=Shell)

See also