vitalik / django-ninja

💨 Fast, Async-ready, Openapi, type hints based framework for building APIs
https://django-ninja.dev
MIT License
7.18k stars 425 forks source link

Throttling support? #321

Open ddahan opened 2 years ago

ddahan commented 2 years ago

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.

mom1 commented 2 years ago

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

ddahan commented 2 years ago

@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
mom1 commented 2 years ago

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

SmileyChris commented 2 years ago

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

ddahan commented 2 years ago

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

metalshanked commented 2 years ago

Looks like Does not seem to work with Async APIs

maxmorlocke commented 2 years ago

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."
   )