Skip to content

Commit 008afad

Browse files
author
Michael Brewer
committed
refactor: change to support multiple
1 parent 06174b6 commit 008afad

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

aws_lambda_powertools/event_handler/api_gateway.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ def __init__(
265265
cors: Optional[CORSConfig] = None,
266266
debug: Optional[bool] = None,
267267
serializer: Optional[Callable[[Dict], str]] = None,
268-
prefix: Optional[str] = None,
268+
strip_prefixes: Optional[List[str]] = None,
269269
):
270270
"""
271271
Parameters
@@ -279,8 +279,8 @@ def __init__(
279279
environment variable
280280
serializer : Callable, optional
281281
function to serialize `obj` to a JSON formatted `str`, by default json.dumps
282-
prefix: str, optional
283-
optional prefix removed from the path before doing the routing
282+
strip_prefixes: List[str], optional
283+
optional list of prefixes to be removed from the path before doing the routing
284284
"""
285285
self._proxy_type = proxy_type
286286
self._routes: List[Route] = []
@@ -290,7 +290,7 @@ def __init__(
290290
self._debug = resolve_truthy_env_var_choice(
291291
env=os.getenv(constants.EVENT_HANDLER_DEBUG_ENV, "false"), choice=debug
292292
)
293-
self._prefix = prefix
293+
self._strip_prefixes = strip_prefixes
294294

295295
# Allow for a custom serializer or a concise json serialization
296296
self._serializer = serializer or partial(json.dumps, separators=(",", ":"), cls=Encoder)
@@ -541,8 +541,11 @@ def _resolve(self) -> ResponseBuilder:
541541

542542
def _remove_prefix(self, path: str) -> str:
543543
"""Remove the configured prefix from the path"""
544-
if self._prefix and path.startswith(self._prefix):
545-
return path[len(self._prefix) :]
544+
if self._strip_prefixes:
545+
for prefix in self._strip_prefixes:
546+
if path.startswith(prefix + "/"):
547+
return path[len(prefix) :]
548+
546549
return path
547550

548551
def _not_found(self, method: str) -> ResponseBuilder:

tests/functional/event_handler/test_api_gateway.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -773,12 +773,16 @@ def get_color() -> Dict:
773773

774774
@pytest.mark.parametrize(
775775
"path",
776-
[pytest.param("/pay/foo", id="prefix matches path"), pytest.param("/foo", id="prefix does not match path")],
776+
[
777+
pytest.param("/pay/foo", id="prefix matches path"),
778+
pytest.param("/payment/foo", id="prefix matches path"),
779+
pytest.param("/foo", id="prefix does not match path"),
780+
],
777781
)
778782
def test_remove_prefix(path: str):
779783
# GIVEN a configured prefix of `/pay`
780784
# AND events paths `/pay/foo` or `/foo`
781-
app = ApiGatewayResolver(prefix="/pay")
785+
app = ApiGatewayResolver(strip_prefixes=["/pay", "/payment"])
782786

783787
@app.get("/foo")
784788
def foo():

0 commit comments

Comments
 (0)