Skip to content

Commit

Permalink
Format
Browse files Browse the repository at this point in the history
  • Loading branch information
ahopkins committed Dec 7, 2023
1 parent 4037354 commit 7663531
Show file tree
Hide file tree
Showing 7 changed files with 31 additions and 93 deletions.
2 changes: 2 additions & 0 deletions sanic_routing/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,12 @@ def __init__(
message: str = "Method does not exist",
method: Optional[str] = None,
allowed_methods: Optional[Set[str]] = None,
path: Optional[str] = None,
):
super().__init__(message)
self.method = method
self.allowed_methods = allowed_methods
self.path = path


class FinalizationError(BaseException):
Expand Down
24 changes: 5 additions & 19 deletions sanic_routing/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,7 @@ def __init__(self, *routes) -> None:
self.pattern_idx = 0

def __str__(self):
display = (
f"path={self.path or self.router.delimiter} len={len(self.routes)}"
)
display = f"path={self.path or self.router.delimiter} len={len(self.routes)}"
return f"<{self.__class__.__name__}: {display}>"

def __repr__(self) -> str:
Expand All @@ -97,11 +95,7 @@ def __getattr__(self, key):

def finalize(self):
self.methods_index = Immutable(
{
method: route
for route in self._routes
for method in route.methods
}
{method: route for route in self._routes for method in route.methods}
)

def prioritize_routes(self) -> None:
Expand Down Expand Up @@ -155,14 +149,8 @@ def handler2(...):
for current_route in self:
if (
current_route == other_route
or (
current_route.requirements
and not other_route.requirements
)
or (
not current_route.requirements
and other_route.requirements
)
or (current_route.requirements and not other_route.requirements)
or (not current_route.requirements and other_route.requirements)
) and not append:
if not overwrite:
raise RouteExists(
Expand Down Expand Up @@ -191,9 +179,7 @@ def dynamic_path(self) -> bool:
@property
def methods(self) -> FrozenSet[str]:
""""""
return frozenset(
[method for route in self for method in route.methods]
)
return frozenset([method for route in self for method in route.methods])

@property
def routes(self) -> Sequence[Route]:
Expand Down
7 changes: 2 additions & 5 deletions sanic_routing/patterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,7 @@ def __init__(self, **kwargs):
)
if match.group(2) == "path":
raise InvalidUsage(
"Extension parameter matching does not support the "
"`path` type."
"Extension parameter matching does not support the " "`path` type."
)
ext_type = match.group(3)
regex_type = REGEX_TYPES.get(match.group(2))
Expand Down Expand Up @@ -133,9 +132,7 @@ def process(self, params, value):


EXTENSION = r"[a-z0-9](?:[a-z0-9\.]*[a-z0-9])?"
PARAM_EXT = (
r"<([a-zA-Z_][a-zA-Z0-9_]*)(?:=([a-z]+))?(?::ext(?:=([a-z0-9|\.]+))?)>"
)
PARAM_EXT = r"<([a-zA-Z_][a-zA-Z0-9_]*)(?:=([a-z]+))?(?::ext(?:=([a-z0-9|\.]+))?)>"
REGEX_PARAM_NAME = re.compile(r"^<([a-zA-Z_][a-zA-Z0-9_]*)(?::(.*))?>$")
REGEX_PARAM_EXT_PATH = re.compile(PARAM_EXT)
REGEX_PARAM_NAME_EXT = re.compile(r"^" + PARAM_EXT + r"$")
Expand Down
22 changes: 5 additions & 17 deletions sanic_routing/route.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,11 +204,7 @@ def add_parameter(
pattern = re.compile(pattern)

is_regex = label not in self.router.regex_types
priority = (
0
if is_regex
else list(self.router.regex_types.keys()).index(label)
)
priority = 0 if is_regex else list(self.router.regex_types.keys()).index(label)
self._params[idx] = param_info_class(
name=name,
raw_path=raw_path,
Expand All @@ -233,12 +229,8 @@ def _finalize_params(self):
sorted(params.items(), key=lambda param: self._sorting(param[1]))
)

if not self.regex and any(
":" in param.label for param in self.params.values()
):
raise InvalidUsage(
f"Invalid parameter declaration: {self.raw_path}"
)
if not self.regex and any(":" in param.label for param in self.params.values()):
raise InvalidUsage(f"Invalid parameter declaration: {self.raw_path}")

def _compile_regex(self):
components = []
Expand Down Expand Up @@ -274,9 +266,7 @@ def _compile_regex(self):
else:
components.append(part)

self.pattern = self.router.delimiter + self.router.delimiter.join(
components
)
self.pattern = self.router.delimiter + self.router.delimiter.join(components)

def finalize(self):
self._finalize_params()
Expand Down Expand Up @@ -353,9 +343,7 @@ def parse_parameter_string(self, parameter_string: str):
name, _ = name.split("=", 1)

if not name:
raise ValueError(
f"Invalid parameter syntax: {parameter_string}"
)
raise ValueError(f"Invalid parameter syntax: {parameter_string}")
if label == "string":
warn(
"Use of 'string' as a path parameter type is deprected, "
Expand Down
43 changes: 11 additions & 32 deletions sanic_routing/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def resolve(
orig=path,
extra=extra,
)
raise self.exception(str(e), path=path)
raise e.__class__(str(e), path=path)

if isinstance(route, RouteGroup):
try:
Expand Down Expand Up @@ -125,9 +125,7 @@ def resolve(
# Apply if tuple (from ext) or if it is not a regex matcher
if isinstance(value, tuple):
param.process(params, value)
elif not route.regex or (
route.regex and param.cast is not str
):
elif not route.regex or (route.regex and param.cast is not str):
params[param.name] = value

# Double check that if we made a match it is not a false positive
Expand All @@ -148,9 +146,7 @@ def add(
self,
path: str,
handler: t.Callable,
methods: t.Optional[
t.Union[t.Sequence[str], t.FrozenSet[str], str]
] = None,
methods: t.Optional[t.Union[t.Sequence[str], t.FrozenSet[str], str]] = None,
name: t.Optional[str] = None,
requirements: t.Optional[t.Dict[str, t.Any]] = None,
strict: bool = False,
Expand All @@ -165,8 +161,7 @@ def add(
# - append: if matching path exists, append handler to it
if overwrite and append:
raise FinalizationError(
"Cannot add a route with both overwrite and append equal "
"to True"
"Cannot add a route with both overwrite and append equal " "to True"
)
if priority and not append:
raise FinalizationError(
Expand All @@ -183,11 +178,7 @@ def add(
if self.ALLOWED_METHODS and any(
method not in self.ALLOWED_METHODS for method in methods
):
bad = [
method
for method in methods
if method not in self.ALLOWED_METHODS
]
bad = [method for method in methods if method not in self.ALLOWED_METHODS]
raise BadMethod(
f"Bad method: {bad}. Must be one of: {self.ALLOWED_METHODS}"
)
Expand All @@ -210,9 +201,7 @@ def add(
routes = self.dynamic_routes

# Only URL encode the static parts of the path
path = parts_to_path(
path_to_parts(path, self.delimiter), self.delimiter
)
path = parts_to_path(path_to_parts(path, self.delimiter), self.delimiter)

# We need to clean off the delimiters are the beginning, and maybe the
# end, depending upon whether we are in strict mode
Expand Down Expand Up @@ -387,9 +376,7 @@ def _generate_tree(self) -> None:
self.tree.generate(self._get_non_static_non_path_groups(False))
self.tree.finalize()

def _render(
self, do_compile: bool = True, do_optimize: bool = False
) -> None:
def _render(self, do_compile: bool = True, do_optimize: bool = False) -> None:
# Initial boilerplate for the function source
src = [
Line("def find_route(path, method, router, basket, extra):", 0),
Expand Down Expand Up @@ -448,9 +435,7 @@ def _render(

# Inject regex matching that could not be in the tree
for group in self._get_non_static_non_path_groups(True):
route_container = (
"regex_routes" if group.regex else "dynamic_routes"
)
route_container = "regex_routes" if group.regex else "dynamic_routes"
route_idx: t.Union[str, int] = 0
holder: t.List[Line] = []

Expand Down Expand Up @@ -487,9 +472,7 @@ def _render(
src.append(Line("raise NotFound", 1))
src.extend(delayed)

self.find_route_src = "".join(
map(str, filter(lambda x: x.render, src))
)
self.find_route_src = "".join(map(str, filter(lambda x: x.render, src)))
if do_compile:
try:
syntax_tree = ast.parse(self.find_route_src)
Expand Down Expand Up @@ -549,9 +532,7 @@ def groups(self):

@property
def routes(self):
return tuple(
[route for group in self.groups.values() for route in group]
)
return tuple([route for group in self.groups.values() for route in group])

def _optimize(self, node) -> None:
warn(
Expand All @@ -578,9 +559,7 @@ def _optimize(self, node) -> None:
for test in [current.test, nested.test]:
if isinstance(test, ast.Compare):
values.append(test)
elif isinstance(test, ast.BoolOp) and isinstance(
test.op, ast.And
):
elif isinstance(test, ast.BoolOp) and isinstance(test.op, ast.And):
values.extend(test.values)
else:
...
Expand Down
23 changes: 5 additions & 18 deletions sanic_routing/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,7 @@ def __repr__(self) -> str:

@property
def ident(self) -> str:
prefix = (
f"{self.parent.ident}."
if self.parent and not self.parent.root
else ""
)
prefix = f"{self.parent.ident}." if self.parent and not self.parent.root else ""
return f"{prefix}{self.idx}"

@property
Expand Down Expand Up @@ -230,9 +226,7 @@ def to_src(self) -> t.Tuple[t.List[Line], t.List[Line], t.List[Line]]:
# This is for any inline regex routes. It sould not include,
# path or path-like routes.
if group.regex:
self._inject_regex(
location, return_indent + group_bump, group
)
self._inject_regex(location, return_indent + group_bump, group)
group_bump += 1

# Since routes are grouped, we need to know which to select
Expand Down Expand Up @@ -364,10 +358,7 @@ def _inject_regex(self, location, indent, group):
location.extend(
[
Line(
(
"match = router.matchers"
f"[{group.pattern_idx}].match(path)"
),
("match = router.matchers" f"[{group.pattern_idx}].match(path)"),
indent,
),
Line("if match:", indent),
Expand All @@ -393,9 +384,7 @@ def _sorting(self, item) -> t.Tuple[bool, bool, int, int, int, bool, str]:
type_ * -1,
child.depth * -1,
len(child._children),
not bool(
child.groups and any(group.regex for group in child.groups)
),
not bool(child.groups and any(group.regex for group in child.groups)),
key,
)

Expand All @@ -412,9 +401,7 @@ def get_type(segment):
if ":" in key:
key, param_type = key.split(":", 1)
try:
type_ = list(self.router.regex_types.keys()).index(
param_type
)
type_ = list(self.router.regex_types.keys()).index(param_type)
except ValueError:
type_ = len(list(self.router.regex_types.keys()))
return type_ * -1
Expand Down
3 changes: 1 addition & 2 deletions sanic_routing/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,7 @@ def parts_to_path(parts, delimiter="/"):
if match.group(3):
extension_type = f"={match.group(3)}"
segment = (
f"<{match.group(1)}{filename_type}:"
f"ext{extension_type}>"
f"<{match.group(1)}{filename_type}:" f"ext{extension_type}>"
)
path.append(segment)
except AttributeError:
Expand Down

0 comments on commit 7663531

Please sign in to comment.