API¶
Routes Module¶
-
class
kua.routes.
Routes
(max_depth: int = 40)[source]¶ Route URLs to registered URL patterns.
Thread safety: adding routes is not thread-safe, it should be done on import time, everything else is.
URL matcher supports
:var
for matching dynamic path parts and:*var
for matching one or more parts.Path parts are matched in the following order:
static > var > any-var
.Usage:
routes = kua.Routes() routes.add('api/:foo', {'GET': my_get_controller}) route = routes.match('api/hello-world') route.params # {'foo': 'hello-world'} route.anything # {'GET': my_get_controller} # Matching any path routes.add('assets/:*foo', {}) route = routes.match('assets/user/profile/avatar.jpg') route.params # {'foo': ('user', 'profile', 'avatar.jpg')} # Error handling try: route = routes.match('bad-url/some') except kua.RouteError: raise ValueError('Not found 404') else: # Do something useful here pass
Variables: max_depth – The maximum URL depth (number of parts) willing to match. This only takes effect when one or more URLs matcher make use of any-var (i.e: :*var
), otherwise the depth of the deepest URL is taken.-
add
(url: str, anything: Any) → None[source]¶ Register a URL pattern into the routes for later matching.
It’s possible to attach any kind of object to the pattern for later retrieving. A dict with methods and callbacks, for example. Anything really.
Registration order does not matter. Adding a URL first or last makes no difference.
Parameters: - url – URL
- anything – Literally anything.
-