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
- path: strο
The _reconstructed_ path after the Route has been normalized. Does not contain preceding
/
(see alsouri
)
- 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
- 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 Falseappend (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
- path: strο
The _reconstructed_ path after the Route has been normalized. Does not contain preceding
/
(see alsouri
)
- 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
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:
- 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