]> git.ipfire.org Git - thirdparty/starlette.git/commitdiff
perf: stop use `re` on `get_route_path` (#2701)
authorTrim21 <trim21.me@gmail.com>
Mon, 23 Sep 2024 18:23:34 +0000 (02:23 +0800)
committerGitHub <noreply@github.com>
Mon, 23 Sep 2024 18:23:34 +0000 (20:23 +0200)
* perf: stop use re on get_route_path

* add test

starlette/_utils.py
tests/test__utils.py

index f615eeea4fee078d82fc8a132b0f52728cd47cdd..74c9f24f77c413557cb32957af55b6a7126ef5cc 100644 (file)
@@ -2,7 +2,6 @@ from __future__ import annotations
 
 import asyncio
 import functools
-import re
 import sys
 import typing
 from contextlib import contextmanager
@@ -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
index f46775b4b2490def15b90d6dc49d3b70e45d3182..916f460d4112a8741f28cdda383a8bc0bcaddb34 100644 (file)
@@ -89,6 +89,7 @@ def test_async_nested_partial() -> None:
         ({"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: