From d289ac7e8de469d0f26c0a210d82e1b315ad8304 Mon Sep 17 00:00:00 2001 From: Trim21 Date: Tue, 24 Sep 2024 02:23:34 +0800 Subject: [PATCH] perf: stop use `re` on `get_route_path` (#2701) * perf: stop use re on get_route_path * add test --- starlette/_utils.py | 17 ++++++++++++++--- tests/test__utils.py | 1 + 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/starlette/_utils.py b/starlette/_utils.py index f615eeea4..74c9f24f7 100644 --- a/starlette/_utils.py +++ b/starlette/_utils.py @@ -2,7 +2,6 @@ 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 diff --git a/tests/test__utils.py b/tests/test__utils.py index f46775b4b..916f460d4 100644 --- a/tests/test__utils.py +++ b/tests/test__utils.py @@ -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: