Skip to content

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

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

Successfully merging this pull request may close these issues.

1 participant