django-ninja icon indicating copy to clipboard operation
django-ninja copied to clipboard

Throttling support?

Open ddahan opened this issue 2 years ago • 6 comments

What is the recommended way to handle throttling while using Django ninja? I did not find that term in the doc. Is the any plan to use it? Thanks.

ddahan avatar Jan 11 '22 19:01 ddahan

@ddahan Hi. FYI #99 I use django-ratelimit

mom1 avatar Jan 11 '22 20:01 mom1

@ddahan Hi. FYI #99 I use django-ratelimit

Great, didn't know about this tool. Does it work "as is" with ninja? I mean, can you simply decorate endpoints with @ratelimit(key='ip', rate='5/m') or do you need some tweaks first?

About handling throttling exceptions in Ninja, based on this part of the ratelimit doc, I guess something like this could work:

@api.exception_handler(Ratelimited)
def handle_rate_limited(request, exc):
    # ... handle exception my way

ddahan avatar Jan 11 '22 21:01 ddahan

@ddahan @ratelimit(key='ip', rate='5/m') Yes, it work @api.exception_handler(Ratelimited) Yes, I use it too

mom1 avatar Jan 13 '22 16:01 mom1

That'd be a good addition to the docs. Why not write it up as a pull request? ;)

SmileyChris avatar Jan 20 '22 21:01 SmileyChris

Great idea!

On Thu 20 Jan 2022 at 22:00, Chris Beaven @.***> wrote:

That'd be a good addition to the docs. Why not write it up as a pull request? ;)

— Reply to this email directly, view it on GitHub https://github.com/vitalik/django-ninja/issues/321#issuecomment-1017923077, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAOYBTBBZVSWBE2AZVRBZW3UXBZXFANCNFSM5LXFC22Q . You are receiving this because you were mentioned.Message ID: @.***>

-- David Dahan

ddahan avatar Jan 21 '22 14:01 ddahan

Looks like Does not seem to work with Async APIs

metalshanked avatar Sep 16 '22 05:09 metalshanked

Looks like Does not seem to work with Async APIs

While it's certainly not as elegant as the decorator, you can handle this via usage of django-ratelimit's API's. As an example

from ratelimit.core import is_ratelimited
from ratelimit.exceptions import Ratelimited as RateLimitedError

if is_ratelimited(
    request,
    group="search",
    key="header:X-API-KEY",
    rate="10/s",
    increment=True,
):
   raise RateLimitedError(
       "You have exceeded your quota of requests in an interval.  Please slow down and try again soon."
   )

maxmorlocke avatar Oct 03 '22 20:10 maxmorlocke