Skip to content

Commit ea4dda2

Browse files
committed
Match dynamic routes in ratelimiter.
1 parent b1cfc7b commit ea4dda2

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

starlette_plus/middleware/ratelimiter.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,15 @@
2020

2121
from starlette.requests import Request
2222
from starlette.responses import JSONResponse, Response
23-
from starlette.routing import Route
23+
from starlette.routing import NoMatchFound, Route
2424
from starlette.types import ASGIApp, Receive, Scope, Send
2525

2626
from ..limiter import RateLimit, Store
2727
from ..redis import Redis
2828

2929

3030
if TYPE_CHECKING:
31-
from starlette.routing import Mount, WebSocketRoute
31+
from starlette.routing import Match, Mount, WebSocketRoute
3232
from starlette.types import ASGIApp, Receive, Scope, Send
3333

3434
from ..redis import Redis
@@ -69,7 +69,8 @@ async def default_response(self, request: Request, retry: float) -> Response:
6969

7070
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
7171
if scope["type"] != "http":
72-
return await self.app(scope, receive, send)
72+
await self.app(scope, receive, send)
73+
return
7374

7475
request: Request = Request(scope)
7576
forwarded: str | None = request.headers.get("X-Forwarded-For", None)
@@ -78,8 +79,18 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
7879
route: Route | Mount | WebSocketRoute | None = None
7980

8081
for r in routes:
82+
matches: tuple[Match, Scope] = r.matches(scope=scope)
83+
match_: Scope = matches[1]
84+
if not match_:
85+
continue
86+
87+
try:
88+
r_path: str = r.url_path_for(str(r.name), **match_.get("path_params", {}))
89+
except NoMatchFound:
90+
continue
91+
8192
methods: set[str] | None = r.methods if isinstance(r, Route) else None
82-
if r.path != request.url.path:
93+
if r_path != request.url.path:
8394
continue
8495

8596
if not methods or request.method in methods:

0 commit comments

Comments
 (0)