Skip to content
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

perf: stop use re on get_route_path #2701

Merged
merged 3 commits into from
Sep 23, 2024
Merged
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
17 changes: 14 additions & 3 deletions starlette/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import asyncio
import functools
import re
import sys
import typing
from contextlib import contextmanager
Expand Down Expand Up @@ -84,6 +83,18 @@ def collapse_excgroups() -> typing.Generator[None, None, None]:


def get_route_path(scope: Scope) -> str:
path: str = scope["path"]
root_path = scope.get("root_path", "")
route_path = re.sub(r"^" + root_path + r"(?=/|$)", "", scope["path"])
return route_path
if not root_path:
return path

if not path.startswith(root_path):
return path

if path == root_path:
return ""

if path[len(root_path)] == "/":
return path[len(root_path) :]

return path
1 change: 1 addition & 0 deletions tests/test__utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ async def async_func(
({"path": "/foo-123/bar", "root_path": "/foo"}, "/foo-123/bar"),
({"path": "/foo/bar", "root_path": "/foo"}, "/bar"),
({"path": "/foo", "root_path": "/foo"}, ""),
({"path": "/foo/bar", "root_path": "/bar"}, "/foo/bar"),
],
)
def test_get_route_path(scope: Scope, expected_result: str) -> None:
Expand Down