Skip to content

Annotate request and exception with usage data #324

New issue

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

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

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions django_ratelimit/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from django_ratelimit import ALL, UNSAFE
from django_ratelimit.exceptions import Ratelimited
from django_ratelimit.core import is_ratelimited
from django_ratelimit.core import get_usage


__all__ = ['ratelimit']
Expand All @@ -16,14 +16,24 @@ def decorator(fn):
@wraps(fn)
def _wrapped(request, *args, **kw):
old_limited = getattr(request, 'limited', False)
ratelimited = is_ratelimited(request=request, group=group, fn=fn,
key=key, rate=rate, method=method,
increment=True)

usage = get_usage(request=request, group=group, fn=fn,
key=key, rate=rate, method=method,
increment=True)
if usage is None:
ratelimited = False
else:
ratelimited = usage['should_limit']

request.limited = ratelimited or old_limited
request.usage = usage

if ratelimited and block:
cls = getattr(
settings, 'RATELIMIT_EXCEPTION_CLASS', Ratelimited)
raise (import_string(cls) if isinstance(cls, str) else cls)()
exc = (import_string(cls) if isinstance(cls, str) else cls)()
exc.usage = usage
raise exc
return fn(request, *args, **kw)
return _wrapped
return decorator
Expand Down