routes
The Router that maps URLs to handler functions.
Defines URL normalization helpers (normalize_url, clean_url) and the
Router class, which stores registered routes with their introspected
signatures and prepares handler arguments by running the parameter pipeline
(collect, normalize, bind, convert, diagnose) over each incoming request.
SYSTEM_URL_PREFIX = '--'
module-attribute
Prefix reserved for the URLs of Drafter's own system routes, such as --about.
Router()
dataclass
Map URL paths to route handler functions and prepare request arguments.
Attributes:
| Name | Type | Description |
|---|---|---|
routes |
dict[str, Callable]
|
Dictionary mapping normalized URL strings to callable handlers. |
route_names |
dict[str, str]
|
Dictionary mapping cleaned function-style names to the
normalized URL they were registered under, used as the name-based
fallback in |
signatures |
dict[str, RouteSignatureSpec]
|
Dictionary mapping normalized URL strings to RouteSignatureSpec data. |
add_route(url, func)
Register a route handler for the given URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Route URL path. |
required |
func
|
Callable
|
Handler function to call for requests to this URL. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dict with the registered "url", the handler's "signature" rendered as a string, and its request "parameters". |
build_argument_representation(signature, args, kwargs)
Generate a string representation of function call arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signature
|
RouteSignatureSpec
|
Introspection data for the target function. |
required |
args
|
list[Any]
|
Positional arguments list. |
required |
kwargs
|
dict[str, Any]
|
Keyword arguments dictionary. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Function signature string like "func(arg1, kwarg=val2)". |
clear()
Remove all registered routes and signatures.
find_missing_arguments(url, injected_names=())
Name the parameters a route could not fill if it got no values.
A page opened from its address (a reload, a bookmark, a shared link) arrives with no form fields, component arguments, or event values. This runs the same binding a real request gets, with an empty payload, so the answer always agrees with what the route would actually report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The route to check. |
required |
injected_names
|
Iterable[str]
|
Names of the framework values Drafter passes by
parameter name (such as |
()
|
Returns:
| Type | Description |
|---|---|
list[str]
|
The required parameters left without a value, in declaration order. Empty when the route can run as it is, and also when no such route exists (visiting it reports that on its own). |
get_route(url)
Retrieve the handler function for a given URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Route URL path to look up. |
required |
Returns:
| Type | Description |
|---|---|
Callable | None
|
Optional[Callable]: Handler function or None if not found. |
get_signature(request)
Retrieve function signature metadata for a request URL.
The URL is resolved exactly as get_route resolves it, so the
signature always belongs to the handler that will be called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Request with URL to look up. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
RouteSignatureSpec |
RouteSignatureSpec
|
Signature metadata for the route. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no signature is registered for the URL. |
has_route(url)
Check whether a route exists for the given URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Route URL path to check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if route exists, False otherwise. |
prepare_arguments(request, current_state, configuration, extra_dependencies)
Prepare positional and keyword arguments for route invocation.
Runs the deterministic five-stage parameter pipeline:
- Collect: build one payload (with per-key source provenance) from the event detail, component arguments, form fields, and framework metadata.
- Normalize: apply component-declared aliases.
- Bind: match payload values to the route signature, understanding defaults, injected dependencies (state, configuration), and var-keyword parameters.
- Convert: strictly convert explicitly typed parameters through the shared converter registry; pass untyped parameters through raw.
- Diagnose: raise on missing required parameters and failed conversions; warn on unused and colliding payload keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Incoming client request with form data. |
required |
current_state
|
SiteState
|
Current application state (injected if expected). |
required |
configuration
|
ClientServerConfiguration
|
Server configuration context. |
required |
extra_dependencies
|
dict[str, Any]
|
Framework values injected by parameter name. |
required |
Returns:
| Type | Description |
|---|---|
tuple[list[Any], dict[str, Any], str, tuple[dict, ...]]
|
Tuple of (args list, kwargs dict, representation string, per-parameter provenance dicts for the debug panel). |
Raises:
| Type | Description |
|---|---|
ParameterBindingError
|
If required parameters are missing or values cannot be converted to the annotated types. |
preprocess_button_press(request, kwargs)
Extract button metadata from the request.
Reads button_pressed from the Request object (set by the client). Falls back to extracting from kwargs for backward compatibility with older clients (e.g., the TypeScript/Skulpt bridge).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
The incoming request with button_pressed field. |
required |
kwargs
|
dict[str, Any]
|
Form data dict (modified to remove button key if present as fallback). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Button namespace/identifier, or empty string if no button. |
report_diagnostics(request, diagnostics)
Log warning diagnostics and raise if any errors were produced.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Associated request for error context. |
required |
diagnostics
|
tuple[RouteDiagnostic, ...]
|
Diagnostics collected across the pipeline stages. |
required |
Raises:
| Type | Description |
|---|---|
ParameterBindingError
|
If any error-severity diagnostics exist. |
reset()
Reset router state. Note that this does not remove routes or signatures, because those are meant to survive server resets.
Currently, this method is a no-op.
resolve_url(url)
Find the registered URL that a requested URL refers to.
An exact match on the normalized URL always wins. Otherwise the URL
is matched by its cleaned, function-style name (so mypage finds a
route registered as /my-page). System URLs (see is_system_url)
only ever match exactly: cleaning would strip the -- prefix and
confuse --about with a student route named about.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Route URL path to look up. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The normalized URL the route was registered under (a key of
|
clean_url(url)
Turns a URL into a heavily normalized form for matching against route function names, instead of explicit URLs.
The following transformations are applied: - Strips leading and trailing whitespace. - Strips leading and trailing slashes. - Internal slashes are converted to underscores. - Single dots are ignored. - Double dots delete the previous path segment, if any. - Non-valid characters are removed (only alphanumeric characters and underscores are kept).
is_system_url(url)
Checks whether a URL is in the namespace reserved for system routes.
System URLs start with -- (ignoring surrounding whitespace and slashes),
which keeps them apart from student routes: --about is Drafter's About
page, while about is an ordinary route a student may define.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The URL to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the URL's first path segment starts with |
Example
is_system_url("--about") # True is_system_url("about") # False
normalize_url(url)
Turns a URL into a normalized form for consistent route matching.
This function performs the following transformations: - Strips leading and trailing whitespace. - Strips trailing slashes. - Prepends "/" if the URL is non-empty and does not already start with "/". - Converts empty URLs to "/index". - Single dots are ignored - Double dots delete the previous path segment, if any.