GitHub

API reference for Router.

class Router[A]

Routes by method and path. Paths are /-rooted patterns with :name parameters (:name(regex), :name? last, :: for a literal colon) and a trailing * wildcard; "*" matches all.

Attributes

AttributeTypeDescription
configRouterConfig = field(default_factory=RouterConfig)
max_param_length_exceededbool = False

Functions

__init__

__init__(config=RouterConfig(), max_param_length_exceeded=False, _routes=list[_Route](), _trees=dict[str, StaticNode](), _static=dict[str, dict[str, Handler[object]]](), _single_param=dict[str, dict[str, Handler[object]]](), _single_param_disabled=set[str]()) -> None
ParameterTypeDescription
configRouterConfig = RouterConfig()
max_param_length_exceededbool = False
_routeslist[_Route] = list[_Route]()
_treesdict[str, StaticNode] = dict[str, StaticNode]()
_staticdict[str, dict[str, Handler[object]]] = dict[str, dict[str, Handler[object]]]()
_single_paramdict[str, dict[str, Handler[object]]] = dict[str, dict[str, Handler[object]]]()
_single_param_disabledset[str] = set[str]()

on

on(method, path, handler) -> None

Register handler; a duplicate method and pattern raises ValueError.

ParameterTypeDescription
methodstr | Iterable[str]
pathstr
handlerA
def on(self, method: str | Iterable[str], path: str, handler: A) -> None:
    """Register ``handler``; a duplicate method and pattern raises
    ``ValueError``."""
    optional = _OPTIONAL_PARAM.search(path)
    if optional is not None:
        if optional.end() != len(path):
            raise ValueError("Optional Parameter needs to be the last parameter of the path")
        self.on(method, _OPTIONAL_PARAM.sub(r"\1\2", path, count=1), handler)
        self.on(method, _OPTIONAL_PARAM.sub(r"\2", path, count=1) or "/", handler)
        return
    if self.config.ignore_duplicate_slashes:
        path = remove_duplicate_slashes(path)
    if self.config.ignore_trailing_slash:
        path = trim_last_slash(path)
    for name in [method] if isinstance(method, str) else method:
        self._on(name, path, handler)

all

all(path, handler) -> None
ParameterTypeDescription
pathstr
handlerA
def all(self, path: str, handler: A) -> None:
    self.on(HTTP_METHODS, path, handler)

has

has(method, path) -> bool
ParameterTypeDescription
methodstr
pathstr

Returns bool

def has(self, method: str, path: str) -> bool:
    tree = self._trees.get(method)
    if tree is None:
        return False
    node = tree.get_static_child(path)
    return node is not None and node.is_leaf

find

find(method, path) -> FindResult[A] | None
ParameterTypeDescription
methodstr
pathstr

Returns FindResult[A] | None

def find(self, method: str, path: str) -> FindResult[A] | None:  # noqa: PLR0911, PLR0912, PLR0915
    self.max_param_length_exceeded = False
    current: Node | None = self._trees.get(method)
    if current is None:
        return None
    query = ""
    decode_param = False
    clean = _is_clean(path)
    if not clean:
        if not path.startswith("/"):
            path = _FULL_PATH.sub("/", path, count=1)
        try:
            path, query, decode_param = _safe_decode_uri(path)
        except ValueError:
            return None
        if self.config.ignore_duplicate_slashes:
            path = remove_duplicate_slashes(path)
        if self.config.ignore_trailing_slash:
            path = trim_last_slash(path)
    origin = path
    if not clean and not self.config.case_sensitive:
        path = path.lower()
    max_length = self.config.max_param_length

    def result(handle: Handler[object], values: list[str]) -> FindResult[A]:
        return FindResult(
            cast("A", handle.handler),
            handle.create_params(values),
            _query_string.parse(query),
        )

    static = self._static.get(method)
    if static is not None and (handle := static.get(path)) is not None:
        return result(handle, [])
    single = self._single_param.get(method)
    if single is not None:
        prefix_length = path.rfind("/") + 1
        handle = single.get(path[:prefix_length])
        if handle is not None and len(path) > prefix_length:
            param = origin[prefix_length:]
            if decode_param:
                param = _safe_decode_component(param)
            if len(param) <= max_length:
                return result(handle, [param])
            self.max_param_length_exceeded = True

    assert isinstance(current, StaticNode)
    index = len(current.prefix)
    params: list[str] = []
    length = len(path)
    stack: list[Brother] = []
    node: Node | None
    while True:
        if index == length and current.handler is not None:
            return result(current.handler, params)
        node = current.next_node(path, index, stack, len(params))
        if node is None:
            if not stack:
                return None
            brother = stack.pop()
            index = brother.path_index
            del params[brother.params_count :]
            node = brother.node
        current = node
        while True:
            if isinstance(current, StaticNode):
                index += len(current.prefix)
                break
            if isinstance(current, WildcardNode):
                param = origin[index:]
                params.append(_safe_decode_component(param) if decode_param else param)
                index = length
                break
            end = origin.find("/", index)
            if end == -1:
                end = length
            param = origin[index:end]
            if decode_param:
                param = _safe_decode_component(param)
            retry = False
            if current.regex is not None:
                matched = current.regex.match(param)
                if matched is None:
                    retry = True
                else:
                    groups = [group or "" for group in matched.groups()]
                    if any(len(group) > max_length for group in groups):
                        self.max_param_length_exceeded = True
                        retry = True
                    else:
                        params.extend(groups)
            elif len(param) > max_length:
                self.max_param_length_exceeded = True
                retry = True
            else:
                params.append(param)
            if retry:
                if not stack:
                    return None
                brother = stack.pop()
                index = brother.path_index
                del params[brother.params_count :]
                current = brother.node
                continue
            index = end
            break