Skip to content

route.py

Provides route class.

Route dataclass

Represents a single route mapping.

Parameters:

Name Type Description Default
endpoint str

Route endpoint. Can contain optional path parameters with converter names.

required
handler Callable

Request handler.

required
methods Iterable[str]

Allowed request methods.

required
Source code in jetweb/routing/route.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@dataclass
class Route:
    """
    Represents a single route mapping.

    :param endpoint: Route endpoint. Can contain optional path parameters with converter names.
    :param handler: Request handler.
    :param methods: Allowed request methods.
    """
    endpoint: str
    handler: Callable
    methods: Iterable[str]
    _pattern: Pattern = field(init=False, repr=False)

    def __post_init__(self):
        self.endpoint = normalize_endpoint(self.endpoint)
        self._pattern = create_pattern(self.endpoint, CONVERTERS)

    def match_endpoint(self, endpoint: str) -> tuple[bool, dict]:
        """
        Match a request endpoint against this route's pattern.

        :param endpoint: Request endpoint for matching.
        :returns: True if endpoint is matched and parsed path parameters.
        """
        match = self._pattern.match(endpoint)
        path_params = match.groupdict() if match else {}

        return bool(match), convert_path_params(self.endpoint, path_params, CONVERTERS)

    def match_method(self, method: str) -> bool:
        """
        Match a request method against this route's allowed methods.

        :returns: True if method is matched.
        """
        return method in self.methods or "*" in self.methods

match_endpoint(endpoint)

Match a request endpoint against this route's pattern.

Parameters:

Name Type Description Default
endpoint str

Request endpoint for matching.

required

Returns:

Type Description
tuple[bool, dict]

True if endpoint is matched and parsed path parameters.

Source code in jetweb/routing/route.py
33
34
35
36
37
38
39
40
41
42
43
def match_endpoint(self, endpoint: str) -> tuple[bool, dict]:
    """
    Match a request endpoint against this route's pattern.

    :param endpoint: Request endpoint for matching.
    :returns: True if endpoint is matched and parsed path parameters.
    """
    match = self._pattern.match(endpoint)
    path_params = match.groupdict() if match else {}

    return bool(match), convert_path_params(self.endpoint, path_params, CONVERTERS)

match_method(method)

Match a request method against this route's allowed methods.

Returns:

Type Description
bool

True if method is matched.

Source code in jetweb/routing/route.py
45
46
47
48
49
50
51
def match_method(self, method: str) -> bool:
    """
    Match a request method against this route's allowed methods.

    :returns: True if method is matched.
    """
    return method in self.methods or "*" in self.methods