laurentS / slowapi

A rate limiter for Starlette and FastAPI
https://pypi.org/project/slowapi/
MIT License
1.16k stars 74 forks source link

Can global limits make this in FastAPI? #129

Open stilleshan opened 1 year ago

stilleshan commented 1 year ago

If I set the global limit to "10/minute" with default_limits, can some API endpoints receive the global limit even if they don't have a limit decorator, while other endpoints with limit decorators receive the limits set by the decorators?

Here's an example: I want to limit access to the /test endpoint to 3 times, and then limit access to both the / and /home endpoints to a total of 7 times. I don't want to add decorators to / and /home separately.

limiter = Limiter(key_func=get_remote_address, default_limits=["10/minute"])
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.add_middleware(SlowAPIMiddleware)

@app.get("/")
async def root_page(request: Request):
    return 'root'

@app.get("/home")
async def homepage(request: Request):
    return 'home'

@app.get("/test")
@limiter.limit("3/minute")
async def test(request: Request):
    return 'test'
laurentS commented 1 year ago

Hi @stilleshan yes, this should work. See this example in the docs. If your code above does not work, then I believe you've found a bug.

Snawe commented 4 months ago

Hi! just stumbled accross this issue. I tried to create default limits for all routes without the decorator like this

limiter = Limiter(key_func=get_remote_address, default_limits=["5/minute"], storage_uri="mongodb://localhost:27017", strategy="moving-window")

But it seems to not work. The mongodb storrage seems not to be the issue, because adding the @limiter.limit("5/minute") decorator directly to a route works. Can it be that default_limits is bugged?

laurentS commented 4 months ago

Hi @Snawe yes, it could be a bug in the middleware. But can you check a few points first?

Please let us know if any of the above fixes your problem. It might be worth adjusting the docs if they're unclear (or fixing the bug, if indeed you found one!).

Snawe commented 3 months ago

Hi @laurentS ! Thanks for your reply and sorry for my very late response. It was actually me. I commented out the line to add the middleware during some testing. everything works fine! Thanks.