slowapi icon indicating copy to clipboard operation
slowapi copied to clipboard

the function _find_route_handler is not working well when using generate route

Open df-cgdm opened this issue 1 year ago • 0 comments

Describe the bug The function _find_route_handler is not return the good route handler when using route with variable

To Reproduce I have two route handler

@app.api_route("/health", include_in_schema=True)
@limiter.exempt
async def health():
{
    return Response(content='OK')
}

@app.api_route(
    "/{full_path:path}",
    methods=["GET", "POST"],
)
async def proxy(
    request: Request, full_path: str
) -> Response:
    return proxy_request(full_path)

The problem is that the limiter.exempt is not working on /health route

Expected behavior Limiter should be used for the health end poing

Your app (please complete the following information):

  • fastapi version 0.115.6
  • slowapi version 0.1.9

Additional context The problem is in the function _find_route_handler which return the latest handler matching the route when fastapi is using the first

def _find_route_handler(
    routes: Iterable[BaseRoute], scope: Scope
) -> Optional[Callable]:
    handler = None
    for route in routes:
        match, _ = route.matches(scope)
        if match == Match.FULL and hasattr(route, "endpoint"):
            handler = route.endpoint  # type: ignore
    return handler

it should be changed by

def _find_route_handler(
    routes: Iterable[BaseRoute], scope: Scope
) -> Optional[Callable]:
    handler = None
    for route in routes:
        match, _ = route.matches(scope)
        if match == Match.FULL and hasattr(route, "endpoint"):
            handler = route.endpoint  # type: ignore
            break
    return handler

df-cgdm avatar Feb 07 '25 10:02 df-cgdm