Sanic-Routing

23.12.0 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `Router`, add various types of routes (simple, string parameter, path parameter), and then perform route lookups using `router.get()`. It also shows how to handle `NotFound` exceptions for non-existent routes.

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__}")

view raw JSON →