Core routing component for Sanic
Slowing down. Last release over 2 years ago, little activity since. Fine for existing code; think twice for a new project.
pip install sanic-routingSanic Routing
Background
Beginning in v21.3, Sanic makes use of this new AST-style router in two use cases:
- Routing paths; and
- Routing signals.
Therefore, this package comes with a BaseRouter that needs to be subclassed in order to be used for its specific needs.
Most Sanic users should never need to concern themselves with the details here.
Basic Example
A simple implementation:
import logging
from sanic_routing import BaseRouter
logging.basicConfig(level=logging.DEBUG)
class Router(BaseRouter):
def get(self, path, *args, **kwargs):
return self.resolve(path, *args, **kwargs)
router = Router()
router.add("/<foo>", lambda: ...)
router.finalize()
router.tree.display()
logging.info(router.find_route_src)
route, handler, params = router.get("/matchme", method="BASE", extra=None)
The above snippet uses router.tree.display() to show how the router has decided to arrange the routes into a tree. In this simple example:
<Node: level=0>
<Node: part=__dynamic__:str, level=1, groups=[<RouteGroup: path=<foo:str> len=1>], dynamic=True>
We can can see the code that the router has generated for us. It is available as a string at router.find_route_src.
def find_route(path, method, router, basket, extra):
parts = tuple(path[1:].split(router.delimiter))
num = len(parts)
# node=1 // part=__dynamic__:str
if num == 1: # CHECK 1
try:
basket['__matches__'][0] = str(parts[0])
except ValueError:
pass
else:
# Return 1
return router.dynamic_routes[('<__dynamic__:str>',)][0], basket
raise NotFound
FYI: If you are on Python 3.9, you can see a representation of the source after compilation at router.find_route_src_compiled
What's it doing?
Therefore, in general implementation requires you to:
- Define a router with a
getmethod; - Add one or more routes;
- Finalize the router (
router.finalize()); and - Call the router's
getmethod.
NOTE: You can call router.finalize(False) if you do not want to compile the source code into executable form. This is useful if you only intend to review the generated output.
Every time you call router.add you create one (1) new Route instance. Even if that one route is created with multiple methods, it generates a single instance. If you another that has a similar path structure (but, perhaps has differen methods) they will be grouped together into a . It is worth also noting that a is created the first time you call , but subsequent similar routes will reuse the existing grouping instance.