Skip to content

Commit

Permalink
Enhance route naming system in Sanic mixins
Browse files Browse the repository at this point in the history
Sanic mixins have been updated to support more informative route naming. `_generate_name()` is now enhanced to include methods and URIs as part of the route name, providing more context about the route configuration. The update also takes care of potential naming conflicts in different scenarios.
  • Loading branch information
hamed committed Mar 25, 2024
1 parent 1495b64 commit 804c311
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
11 changes: 10 additions & 1 deletion sanic/mixins/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ class BaseMixin(metaclass=SanicMeta):
name: str
strict_slashes: Optional[bool]

def _generate_name(self, *objects) -> str:
def _generate_name(self, *objects, methods=None, uri=None) -> str:
name = None
named_route = False

for obj in objects:
if obj:
if isinstance(obj, str):
name = obj
named_route = True
break

try:
Expand All @@ -32,6 +34,13 @@ def _generate_name(self, *objects) -> str:
raise ValueError("Could not generate a name for handler")

if not name.startswith(f"{self.name}."):
if not named_route:
if methods:
methods = "_".join(methods)
name = f"{name}_{methods}"
if uri:
# uri = uri.replace("/", "/")
name = f"{name}_{uri}"
name = f"{self.name}.{name}"

return name
2 changes: 1 addition & 1 deletion sanic/mixins/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def decorator(handler):
# variable will be a tuple of (existing routes, handler fn)
_, handler = handler

name = self._generate_name(name, handler)
name = self._generate_name(name, handler, methods=methods, uri=uri)

if isinstance(host, str):
host = frozenset([host])
Expand Down

0 comments on commit 804c311

Please sign in to comment.