Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion slowapi/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,28 @@
from slowapi import Limiter, _rate_limit_exceeded_handler


def _get_nested_routes(route: BaseRoute) -> Optional[Iterable[BaseRoute]]:
nested_routes = getattr(route, "routes", None)
if nested_routes is not None:
return nested_routes

original_router = getattr(route, "original_router", None)
return getattr(original_router, "routes", None)


def _find_route_handler(
routes: Iterable[BaseRoute], scope: Scope
) -> Optional[Callable]:
handler = None
for route in routes:
match, _ = route.matches(scope)
match, child_scope = route.matches(scope)
if match == Match.FULL and hasattr(route, "endpoint"):
handler = route.endpoint # type: ignore
elif match in (Match.FULL, Match.PARTIAL):
nested_routes = _get_nested_routes(route)
if nested_routes is not None:
nested_scope = {**scope, **child_scope}
handler = _find_route_handler(nested_routes, nested_scope) or handler
return handler


Expand Down
17 changes: 17 additions & 0 deletions tests/test_fastapi_extension.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import hiro # type: ignore
import pytest # type: ignore
from fastapi import APIRouter
from starlette.requests import Request
from starlette.responses import PlainTextResponse, Response
from starlette.testclient import TestClient
Expand All @@ -9,6 +10,22 @@


class TestDecorators(TestSlowapi):
def test_default_limit_with_included_router(self, build_fastapi_app):
app, limiter = build_fastapi_app(
key_func=lambda: "test", default_limits=["1/minute"]
)
router = APIRouter(prefix="/api")

@router.get("/t1")
async def t1(request: Request):
return PlainTextResponse("test")

app.include_router(router)

client = TestClient(app)
assert client.get("/api/t1").status_code == 200
assert client.get("/api/t1").status_code == 429

def test_single_decorator(self, build_fastapi_app):
app, limiter = build_fastapi_app(key_func=get_ipaddr)

Expand Down