Skip to content

Commit 411dc2b

Browse files
committed
fix: streamlined regexes
1 parent 6c38ef6 commit 411dc2b

File tree

2 files changed

+35
-6
lines changed

2 files changed

+35
-6
lines changed

aws_lambda_powertools/event_handler/api_gateway.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -520,7 +520,7 @@ def __init__(
520520
cors: Optional[CORSConfig] = None,
521521
debug: Optional[bool] = None,
522522
serializer: Optional[Callable[[Dict], str]] = None,
523-
strip_prefixes: Optional[List[str]] = None,
523+
strip_prefixes: Optional[List[Union[str, Pattern]]] = None,
524524
):
525525
"""
526526
Parameters
@@ -534,9 +534,9 @@ def __init__(
534534
environment variable
535535
serializer : Callable, optional
536536
function to serialize `obj` to a JSON formatted `str`, by default json.dumps
537-
strip_prefixes: List[str], optional
537+
strip_prefixes: List[Union[str, Pattern]], optional
538538
optional list of prefixes to be removed from the request path before doing the routing. This is often used
539-
with api gateways with multiple custom mappings.
539+
with api gateways with multiple custom mappings. Each prefix can be a static string or a compiled regex
540540
"""
541541
self._proxy_type = proxy_type
542542
self._dynamic_routes: List[Route] = []
@@ -713,10 +713,18 @@ def _remove_prefix(self, path: str) -> str:
713713
return path
714714

715715
for prefix in self._strip_prefixes:
716-
if path == prefix:
717-
return "/"
718-
path = re.sub(rf"^/?({prefix})/", r"/", path)
716+
if isinstance(prefix, str):
717+
if path == prefix:
718+
return "/"
719+
720+
if self._path_starts_with(path, prefix):
721+
return path[len(prefix) :]
722+
723+
if isinstance(prefix, Pattern):
724+
path = re.sub(prefix, "", path)
719725

726+
# When using regexes, we might get into a point where everything is removed
727+
# from the string, so we check if it's empty and change it accordingly.
720728
if not path:
721729
path = "/"
722730

tests/functional/event_handler/test_api_gateway.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import base64
22
import json
3+
import re
34
import zlib
45
from copy import deepcopy
56
from decimal import Decimal
@@ -1077,6 +1078,26 @@ def foo():
10771078
assert response["statusCode"] == 200
10781079

10791080

1081+
@pytest.mark.parametrize(
1082+
"path",
1083+
[
1084+
pytest.param("/stg/foo", id="path matched pay prefix"),
1085+
pytest.param("/dev/foo", id="path matched pay prefix with multiple numbers"),
1086+
pytest.param("/foo", id="path does not start with any of the prefixes"),
1087+
],
1088+
)
1089+
def test_remove_prefix_by_regex(path: str):
1090+
app = ApiGatewayResolver(strip_prefixes=[re.compile(r"/(dev|stg)")])
1091+
1092+
@app.get("/foo")
1093+
def foo():
1094+
...
1095+
1096+
response = app({"httpMethod": "GET", "path": path}, None)
1097+
1098+
assert response["statusCode"] == 200
1099+
1100+
10801101
@pytest.mark.parametrize(
10811102
"prefix",
10821103
[

0 commit comments

Comments
 (0)