Warning

These documents are OUTDATED as of 2023-12-31.

Please refer to the latest version of the documentation at sanic.dev.

Routing

sanic_routing models

class sanic_routing.route.Route(router, raw_path, name, handler, methods, requirements=None, strict=False, unquote=False, static=False, regex=False, overloaded=False, *, priority=0)
Parameters:
  • raw_path (str) –

  • name (str) –

  • handler (Callable[[...], Any]) –

  • methods (FrozenSet[str]) –

  • requirements (Requirements) –

  • strict (bool) –

  • unquote (bool) –

  • static (bool) –

  • regex (bool) –

  • overloaded (bool) –

  • priority (int) –

parse_parameter_string(parameter_string)

Parse a parameter string into its constituent name, type, and pattern

For example:

`text parse_parameter_string('<param_one:[A-z]>')` -> ('param_one', '[A-z]', <class 'str'>, '[A-z]') `

Parameters:

parameter_string (str) – String to parse

Returns:

tuple containing (parameter_name, parameter_type, parameter_pattern)

ctx: SimpleNamespace

A container for route meta-data

extra: SimpleNamespace

A container for route application-data

handler: Callable[[...], Any]

The route handler

methods: FrozenSet[str]

The HTTP methods that the route can handle

name: str

The route name, either generated or as defined in the route definition

parts: Tuple[str, ...]

The raw version of the path exploded (see also segments)

path: str

The _reconstructed_ path after the Route has been normalized. Does not contain preceding / (see also uri)

pattern: str | None

A regex version of the path

property raw_path

The raw path from the route definition

regex: bool

Whether the route requires regular expression evaluation

requirements: Requirements

A representation of the non-path route requirements

property segments: Tuple[str, ...]

Same as parts except generalized so that any dynamic parts do not include param keys since they have no impact on routing.

static: bool

When True, the route does not have any dynamic path parameters

strict: bool

Whether the route should be matched with strict evaluation

unquote: bool

Whether the route should be unquoted after matching if (for example) it is suspected to contain non-URL friendly characters

property uri

Since path does NOT include a preceding β€˜/’, this adds it back.

class sanic_routing.group.RouteGroup(*routes)
merge(group, overwrite=False, append=False)

The purpose of merge is to group routes with the same path, but declarared individually. In other words to group these:

@app.get("/path/to")
def handler1(...):
    ...

@app.post("/path/to")
def handler2(...):
    ...

The other main purpose is to look for conflicts and raise RouteExists

A duplicate route is when: 1. They have the same path and any overlapping methods; AND 2. If they have requirements, they are the same

Parameters:
  • group (RouteGroup) – Incoming route group

  • overwrite (bool, optional) – whether to allow an otherwise duplicate route group to overwrite the existing, if True will not raise exception on duplicates, defaults to False

  • append (bool, optional) – whether to allow an otherwise duplicate route group to append its routes to the existing route group, defaults to False

Raises:

RouteExists – Raised when there is a duplicate

Return type:

None

prioritize_routes()

Sorts the routes in the group by priority

Return type:

None

property depth: int

The number of parts in parts

parts: Tuple[str, ...]

The raw version of the path exploded (see also segments)

path: str

The _reconstructed_ path after the Route has been normalized. Does not contain preceding / (see also uri)

pattern: str | None

A regex version of the path

regex: bool

Whether the route requires regular expression evaluation

segments: Tuple[str, ...]

Same as parts except generalized so that any dynamic parts do not include param keys since they have no impact on routing.

strict: bool

Whether the route should be matched with strict evaluation

unquote: bool

Whether the route should be unquoted after matching if (for example) it is suspected to contain non-URL friendly characters

uri: str

Since path does NOT include a preceding β€˜/’, this adds it back.

sanic.router

class sanic.router.Router(delimiter='/', exception=<class 'sanic_routing.exceptions.NotFound'>, method_handler_exception=<class 'sanic_routing.exceptions.NoMethod'>, route_class=<class 'sanic_routing.route.Route'>, group_class=<class 'sanic_routing.group.RouteGroup'>, stacking=False, cascade_not_found=False)

Bases: BaseRouter

The router implementation responsible for routing a Request object to the appropriate handler.

Parameters:
  • delimiter (str) –

  • exception (Type[NotFound]) –

  • method_handler_exception (Type[NoMethod]) –

  • route_class (Type[Route]) –

  • group_class (Type[RouteGroup]) –

  • stacking (bool) –

  • cascade_not_found (bool) –

add(uri, methods, handler, host=None, strict_slashes=False, stream=False, ignore_body=False, version=None, name=None, unquote=False, static=False, version_prefix='/v', overwrite=False, error_format=None)

Add a handler to the router

Args:

uri (str): The path of the route. methods (Iterable[str]): The types of HTTP methods that should be attached,

example: [β€œGET”, β€œPOST”, β€œOPTIONS”].

handler (RouteHandler): The sync or async function to be executed. host (Optional[str], optional): Host that the route should be on. Defaults to None. strict_slashes (bool, optional): Whether to apply strict slashes. Defaults to False. stream (bool, optional): Whether to stream the response. Defaults to False. ignore_body (bool, optional): Whether the incoming request body should be read.

Defaults to False.

version (Union[str, float, int], optional): A version modifier for the uri. Defaults to None. name (Optional[str], optional): An identifying name of the route. Defaults to None.

Returns:

Route: The route object.

Parameters:
  • uri (str) –

  • methods (Iterable[str]) –

  • handler (Callable[[...], Coroutine[Any, Any, HTTPResponse | None]]) –

  • host (str | Iterable[str] | None) –

  • strict_slashes (bool) –

  • stream (bool) –

  • ignore_body (bool) –

  • version (int | str | float | None) –

  • name (str | None) –

  • unquote (bool) –

  • static (bool) –

  • version_prefix (str) –

  • overwrite (bool) –

  • error_format (str | None) –

Return type:

Route | List[Route]

finalize(*args, **kwargs)

Finalize the router.

Raises:

SanicException: if a route contains a parameter name that starts with β€œ__” and is not in ALLOWED_LABELS

Return type:

None

find_route_by_view_name(view_name, name=None)

Find a route in the router based on the specified view name.

Args:

view_name (str): the name of the view to search for name (Optional[str], optional): the name of the route. Defaults to None.

Returns:

Optional[Route]: the route object

Parameters:
  • view_name (str) –

  • name (str | None) –

Return type:

Route | None

get(path, method, host)

Retrieve a Route object containing the details about how to handle a response for a given request

Parameters:
  • request (Request) – the incoming request object

  • path (str) –

  • method (str) –

  • host (str | None) –

Returns:

details needed for handling the request and returning the correct response

Return type:

Tuple[ Route, RouteHandler, Dict[str, Any]]

Args:

path (str): the path of the route method (str): the HTTP method of the route host (Optional[str]): the host of the route

Raises:

NotFound: if the route is not found MethodNotAllowed: if the method is not allowed for the route

Returns:

Tuple[Route, RouteHandler, Dict[str, Any]]: the route, handler, and match info

property routes_all: Dict[Tuple[str, ...], Route]

Return all routes in the router.

Returns:

Dict[Tuple[str, …], Route]: a dictionary of routes

property routes_dynamic: Dict[Tuple[str, ...], RouteGroup]

Return all dynamic routes in the router.

_Dynamic routes are routes that contain path parameters._

Returns:

Dict[Tuple[str, …], Route]: a dictionary of routes

property routes_regex: Dict[Tuple[str, ...], RouteGroup]

Return all regex routes in the router.

_Regex routes are routes that contain path parameters with regex expressions, or otherwise need regex to resolve._

Returns:

Dict[Tuple[str, …], Route]: a dictionary of routes

property routes_static: Dict[Tuple[str, ...], RouteGroup]

Return all static routes in the router.

_In this context β€œstatic” routes do not refer to the app.static() method. Instead, they refer to routes that do not contain any path parameters._

Returns:

Dict[Tuple[str, …], Route]: a dictionary of routes