Skip to content

Commit

Permalink
Match dynamic routes in ratelimiter.
Browse files Browse the repository at this point in the history
  • Loading branch information
EvieePy committed Apr 26, 2024
1 parent b1cfc7b commit ea4dda2
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions starlette_plus/middleware/ratelimiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@

from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from starlette.routing import Route
from starlette.routing import NoMatchFound, Route
from starlette.types import ASGIApp, Receive, Scope, Send

from ..limiter import RateLimit, Store
from ..redis import Redis


if TYPE_CHECKING:
from starlette.routing import Mount, WebSocketRoute
from starlette.routing import Match, Mount, WebSocketRoute
from starlette.types import ASGIApp, Receive, Scope, Send

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

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

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

for r in routes:
matches: tuple[Match, Scope] = r.matches(scope=scope)
match_: Scope = matches[1]
if not match_:
continue

try:
r_path: str = r.url_path_for(str(r.name), **match_.get("path_params", {}))
except NoMatchFound:
continue

methods: set[str] | None = r.methods if isinstance(r, Route) else None
if r.path != request.url.path:
if r_path != request.url.path:
continue

if not methods or request.method in methods:
Expand Down

0 comments on commit ea4dda2

Please sign in to comment.