-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathregex.py
50 lines (36 loc) · 1.28 KB
/
regex.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
from __future__ import annotations
import re
from uuid import UUID
from typing import Any, Callable
from idom_router import Route
def compile_regex_route(route: Route) -> RegexRoutePattern:
"""Compile simple regex route.
Named regex groups can end with a `__type` suffix to specify a type converter
For example, `(?P<id__int>[0-9]+)` will convert the `id` parameter to an `int`.
Supported types are `int`, `float`, and `uuid`.
"""
pattern = re.compile(route.path)
return RegexRoutePattern(pattern)
class RegexRoutePattern:
def __init__(self, pattern: re.Pattern) -> None:
self.pattern = pattern
self.key = pattern.pattern
def match(self, path: str) -> dict[str, str] | None:
match = self.pattern.match(path)
if match:
params: dict[str, Any] = {}
for k, v in match.groupdict().items():
name, _, type_ = k.partition("__")
try:
params[name] = CONVERTERS.get(type_, DEFAULT_CONVERTER)(v)
except ValueError:
return None
return params
return None
CONVERTERS: dict[str, Callable[[str], Any]] = {
"int": int,
"float": float,
"uuid": UUID,
}
def DEFAULT_CONVERTER(s: str) -> str:
return s