Sanic-Routing
Sanic-Routing is the standalone, high-performance core routing component used by the Sanic web framework. It handles URL parsing, route matching, and parameter extraction, providing a flexible and efficient routing engine. The library maintains an active development pace with frequent updates, typically releasing new versions quarterly.
Warnings
- breaking Route parameters defined with `<name:str>` or `<name:path>` types will no longer match empty strings. Previously, a route like `/users/<user_id:str>` might have matched `/users/` resulting in `user_id=''`.
- deprecated The route parameter types `<foo:string>` and `<foo:number>` were deprecated. They have been replaced with `<foo:str>` and `<foo:float>` respectively.
- gotcha Starting with version 23.6.0, `sanic-routing` will only unquote URI components when casting them to string types. This means that if you're not explicitly casting a parameter, it might retain its URL-encoded state (e.g., `%20` for space).
Install
-
pip install sanic-routing
Imports
- Router
from sanic_routing import Router
Quickstart
from sanic_routing import Router
from sanic_routing.exceptions import NotFound
# Initialize the router
router = Router()
# Define dummy handlers (in a real app, these would be your view functions)
def handler_root(request):
pass
def handler_greet(request, name):
pass
# Add routes to the router
router.add("/", handler_root, methods=["GET"])
router.add("/greet/<name:str>", handler_greet, methods=["GET"])
router.add("/files/<path:path>", lambda req, path: None, methods=["GET"])
# Look up a route by URI and method
try:
# Matching a simple route
handler, params, uri, kwargs, route = router.get("/greet/Alice", "GET")
print(f"Found handler for /greet/Alice: {handler.__name__}")
print(f"Parameters: {params}") # Expected: {'name': 'Alice'}
# Matching a path parameter
handler_path, params_path, uri_path, kwargs_path, route_path = router.get("/files/path/to/document.txt", "GET")
print(f"Found handler for /files/path/to/document.txt: {params_path}") # Expected: {'path': 'path/to/document.txt'}
except NotFound as e:
print(f"Could not find route: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Example of a missing route
try:
router.get("/missing", "GET")
except NotFound as e:
print(f"Attempted to get /missing, caught expected error: {type(e).__name__}")