Skip to content

improve URL matching algorithm in case of ambiguity #2898

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions starlette/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -724,19 +724,45 @@ async def app(self, scope: Scope, receive: Receive, send: Send) -> None:
return

partial = None
full_match_route = None
full_match_best_number_of_path_params = None

for route in self.routes:
# Determine if any route matches the incoming scope,
# and hand over to the matching route if found.
match, child_scope = route.matches(scope)
if match == Match.FULL:
scope.update(child_scope)
await route.handle(scope, receive, send)
return
number_of_path_params = len(child_scope["path_params"])
if number_of_path_params == 0:
scope.update(child_scope)
await route.handle(scope, receive, send)
return
# in case we have 2 routes that fully match the requested URL
# we need to check which one is a stricter match.
# Example:
# we have 2 endpoints:
# /user/{user_id}
# /user/myself
# if the requested URL is /user/myself, then both endpoints are
# a full match, however the last one is a more appropriate choice
# in case of ambiguity
if full_match_route is None or (
full_match_best_number_of_path_params is not None
and number_of_path_params < full_match_best_number_of_path_params
):
full_match_route = route
full_match_scope = child_scope
full_match_best_number_of_path_params = number_of_path_params

elif match == Match.PARTIAL and partial is None:
partial = route
partial_scope = child_scope

if full_match_route is not None:
scope.update(full_match_scope)
await full_match_route.handle(scope, receive, send)
return

if partial is not None:
#  Handle partial matches. These are cases where an endpoint is
# able to handle the request, but is not a preferred option.
Expand Down
26 changes: 25 additions & 1 deletion tests/test_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,16 @@ def user(request: Request) -> Response:
return Response(content, media_type="text/plain")


def user_greet(request: Request) -> Response:
content = "User " + request.path_params["username"] + " greeted"
return Response(content, media_type="text/plain")


def user_action(request: Request) -> Response:
content = "User " + request.path_params["username"] + " action " + request.path_params["action"]
return Response(content, media_type="text/plain")


def user_me(request: Request) -> Response:
content = "User fixed me"
return Response(content, media_type="text/plain")
Expand Down Expand Up @@ -124,6 +134,8 @@ async def websocket_params(session: WebSocket) -> None:
Route("/", endpoint=users),
Route("/me", endpoint=user_me),
Route("/{username}", endpoint=user),
Route("/{username}/greet", endpoint=user_greet),
Route("/{username}/{action}", endpoint=user_action),
Route("/{username}:disable", endpoint=disable_user, methods=["PUT"]),
Route("/nomatch", endpoint=user_no_match),
],
Expand Down Expand Up @@ -212,9 +224,21 @@ def test_router(client: TestClient) -> None:
assert response.url == "http://testserver/users/tomchristie:disable"
assert response.text == "User tomchristie disabled"

response = client.get("/users/notmatch")
assert response.status_code == 200
assert response.text == "User notmatch"

response = client.get("/users/nomatch")
assert response.status_code == 200
assert response.text == "User nomatch"
assert response.text == "User fixed no match"

response = client.get("/users/nomatch/greet")
assert response.status_code == 200
assert response.text == "User nomatch greeted"

response = client.get("/users/nomatch/complimented")
assert response.status_code == 200
assert response.text == "User nomatch action complimented"

response = client.get("/static/123")
assert response.status_code == 200
Expand Down