Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Adds get_usage_extended and the ability to add usage_details to Ratelimited exception #314

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

rgs258
Copy link

@rgs258 rgs258 commented Mar 6, 2024

This change makes it easier to implement a custom decorator that passes usage_details to the exception.

Example:

def ratelimit(group=None, key=None, rate=None, method=ALL, block=True):
    def decorator(fn):
        @wraps(fn)
        def _wrapped(request, *args, **kw):
            old_limited = getattr(request, 'limited', False)
            usage = get_usage_extended(
                request=request,
                group=group,
                fn=fn,
                key=key,
                rate=rate,
                method=method,
                increment=True
            )
            ratelimited = usage['should_limit'] if usage else False
            request.limited = ratelimited or old_limited
            if ratelimited and block:
                cls = getattr(
                    settings, 'RATELIMIT_EXCEPTION_CLASS', Ratelimited)
                raise (import_string(cls) if isinstance(cls, str) else cls)(usage=usage)
            return fn(request, *args, **kw)

        return _wrapped

    return decorator

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant