Skip to content

router

AsgiRouter §

AsgiRouter(routes=None, trailing_slash_match=tree.TrailingSlashMatch.RELAXED)

An AsgiRouter for a Tokamak Application is one or more Routes with an optional configuration for matching trailing slashes or not.

Example

We can define an endpoint handler to associate with any route:

async def some_handler(scope, receive, send):
    message = await receive()
    body = message.get("body") or b"{}"
    payload = json.dumps({"received": json.loads(body)}).encode("utf-8")
    return Response(body=payload)

After that, we can include associate the handler with an endpoint:

AsgiRouter(routes=[
    Route("/", handler=some_handler, methods=["GET"]),
    Route("/files/{dir}/{filepath:*}", handler=some_handler, methods=["POST"]),

])

A dynamic route takes a name for the captured variable and a regex matcher, like so: "/regex/{name:[a-zA-Z]+}/test"

The values matched in paths are always returned in the context as strings.

Parameters:

Name Type Description Default
routes Iterable[Route]

An optional iterable of routes to add.

None
trailing_slash_match TrailingSlashMatch

Strictness property for trailing slashes

tree.TrailingSlashMatch.RELAXED

add_route §

add_route(route)

Adds a single route to the tree.

Parameters:

Name Type Description Default
route Route

A route to add.

required

build_route_tree §

build_route_tree(routes)

Builds the full routing tree.

Parameters:

Name Type Description Default
routes Iterable[Route]

An iterable of routes to add.

required

get_route §

get_route(path)

Search for a matching route by path.

Parameters:

Name Type Description Default
path str

The path to search for.

required

Returns:

Type Description
Tuple[Route, dict[str, str]]

Tuple[Router, context-dictionary]

Raises UnknownEndpoint if no path matched.

Route §

Route(path='', handler=None, methods=None)
A Route for a Tokamak Application represents
  • a path,
  • a request method, and
  • a handler dedicated to requests that match that path and method.
Example

Route("/", handler=any_async_handler, methods=["GET", "POST"])

Parameters:

Name Type Description Default
path str

The http path to add to the router.

''
handler Callable

The async handler (any awaitable callable) to invoke on path match

None
methods List[str]

A list of accepted methods for this endpoint

None
Back to top