Router
wybthon.router¶
router
¶
Routing and the data layer, as in Solid Router 2.0.
Import it from wybthon.router:
- Routes.
create_routertakes a tree ofRoutes (orfile_routes(), one module per page) and returns the router; call it to render. Plain<a href>links navigate within the app.Outletrenders a layout's matched child. - Reading the URL.
use_params,use_search_params,use_location,use_route_matches, anduse_link_state;navigategoes somewhere. - Data.
querywraps an async read so calls are deduplicated and refetch onrevalidate;form_actionmakes an action a form can post to, even before Python has booted, anduse_submissionsreads its history.
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 |
ApiRoute |
A route module's HTTP handlers (server side). |
FormAction |
An action a form can post to; returned by |
Submission |
A settled submission of a form action; see |
Location |
The current URL, read reactively; returned by |
SearchParams |
A decoded query string: each name's last value, plus |
RouteSpec |
A route without a component, for matching in tests and tools. |
LinkState |
Whether a link's target is the current page; returned by |
Params |
The matched route's path parameters, read with |
PreloadArgs |
What a route's |
Route |
A route: a path pattern, the component it shows, and nested routes. |
Router |
A route tree; returned by |
SearchParamsView |
The query string's parameters, read with |
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 |
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 |
use_submissions |
The settled submissions of |
navigate |
Go to |
use_location |
The current URL; read |
match_route |
The best matching route for |
Outlet |
The matched child route, inside a layout route's component (the same as its |
create_router |
Create the app's router from its route tree, as Solid Router 2.0's |
preload_route |
Preload the code and data of the route |
use_link_state |
Whether a link to |
use_params |
The matched route's path parameters: |
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
¶
Tracked accessor for the current path, query, and hash (the request URL on the server).
Query
¶
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 |
Methods:
| Name | Description |
|---|---|
key_for |
The full key of a call with these arguments. |
ApiRoute
dataclass
¶
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 |
Methods:
| Name | Description |
|---|---|
handler |
The module's handler for |
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: |
Methods:
| Name | Description |
|---|---|
bind |
This action with |
on_submit |
Call |
on_settled |
Call |
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 |
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. |
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 |
search |
str
|
The query string, with its leading |
hash |
str
|
The decoded fragment, without its leading |
query |
SearchParams
|
The parsed query string. |
href |
str
|
Path, query, and hash together. |
SearchParams
¶
SearchParams(search: str = '')
RouteSpec
dataclass
¶
LinkState
dataclass
¶
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 |
current |
Accessor[bool]
|
Tracked accessor: same path and same query, ignoring the
hash and parameter order (what |
Params
¶
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']
|
|
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: |
children |
list[Route]
|
Nested routes. |
preload |
Callable[[PreloadArgs], Any] | None
|
Called with |
Router
¶
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 |
SearchParamsView
¶
SearchParamsView(source: Accessor[SearchParams])
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 |
query
¶
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:
- dedupes calls on the server for the lifetime of the request;
- 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;
- refetches, in every memo that read it, when
revalidatenames its key, or when a mutation completes (seeserver_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 |
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
¶
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 |
None
|
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).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
package
|
str
|
The dotted name of the routes package. |
'app.routes'
|
Returns:
| Type | Description |
|---|---|
list[Route]
|
Routes for |
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 |
required |
name
|
str | None
|
The action's name; defaults to the server function's id. |
None
|
Returns:
| Type | Description |
|---|---|
FormAction[P, R]
|
A |
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
¶
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]
|
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
|
|
tuple[Any, dict[str, Any]] | None
|
|
Outlet
¶
Outlet() -> VNode
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.
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 |
required |
base
|
str
|
The base path the app is served under. Links and
|
''
|
preload_links
|
bool
|
Preload a link's route when the pointer rests on it. |
True
|
Returns:
| Type | Description |
|---|---|
Router
|
A |
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
¶
use_params() -> 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
¶
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:
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¶
- Concepts: Router
- Concepts: Full-stack apps: queries, form actions, and file routes
- Examples: Router