1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
|
.. _usage-chapter:
======================
Using Django Ratelimit
======================
.. _usage-decorator:
Use as a decorator
==================
.. versionchanged:: 4.0
Import:
.. code-block:: python
from django_ratelimit.decorators import ratelimit
.. py:decorator:: ratelimit(group=None, key=, rate=None, method=ALL, block=True)
:arg group:
*None* A group of rate limits to count together. Defaults to the
dotted name of the view.
:arg key:
What key to use, see :ref:`Keys <keys-chapter>`.
:arg rate:
*'5/m'* The number of requests per unit time allowed. Valid
units are:
* ``s`` - seconds
* ``m`` - minutes
* ``h`` - hours
* ``d`` - days
Also accepts callables. See :ref:`Rates <rates-chapter>`. A rate
of ``0/s`` disallows all requests. A rate of ``None`` means "no
limit" and will allow all requests.
:arg method:
*ALL* Which HTTP method(s) to rate-limit. May be a string, a
list/tuple of strings, or the special values for ``ALL`` or
``UNSAFE`` (which includes ``POST``, ``PUT``, ``DELETE`` and
``PATCH``).
:arg block:
*True* Whether to block the request instead of annotating.
HTTP Methods
------------
Each decorator can be limited to one or more HTTP methods. The
``method=`` argument accepts a method name (e.g. ``'GET'``) or a list or
tuple of strings (e.g. ``('GET', 'OPTIONS')``).
There are two special shortcuts values, both accessible from the
``ratelimit`` decorator or the ``is_ratelimited`` helper, as well as on
the root ``ratelimit`` module:
.. code-block:: python
from django_ratelimit.decorators import ratelimit
@ratelimit(key='ip', method=ratelimit.ALL)
@ratelimit(key='ip', method=ratelimit.UNSAFE)
def myview(request):
pass
``ratelimit.ALL`` applies to all HTTP methods. ``ratelimit.UNSAFE``
is a shortcut for ``('POST', 'PUT', 'PATCH', 'DELETE')``.
Examples
--------
.. code-block:: python
@ratelimit(key='ip', rate='5/m', block=False)
def myview(request):
# Will be true if the same IP makes more than 5 POST
# requests/minute.
was_limited = getattr(request, 'limited', False)
return HttpResponse()
@ratelimit(key='ip', rate='5/m', block=True)
def myview(request):
# If the same IP makes >5 reqs/min, will raise Ratelimited
return HttpResponse()
@ratelimit(key='post:username', rate='5/m',
method=['GET', 'POST'], block=False)
def login(request):
# If the same username is used >5 times/min, this will be True.
# The `username` value will come from GET or POST, determined by the
# request method.
was_limited = getattr(request, 'limited', False)
return HttpResponse()
@ratelimit(key='post:username', rate='5/m')
@ratelimit(key='post:tenant', rate='5/m')
def login(request):
# Use multiple keys by stacking decorators.
return HttpResponse()
@ratelimit(key='get:q', rate='5/m')
@ratelimit(key='post:q', rate='5/m')
def search(request):
# These two decorators combine to form one rate limit: the same search
# query can only be tried 5 times a minute, regardless of the request
# method (GET or POST)
return HttpResponse()
@ratelimit(key='ip', rate='4/h')
def slow(request):
# Allow 4 reqs/hour.
return HttpResponse()
get_rate = lambda g, r: None if r.user.is_authenticated else '100/h'
@ratelimit(key='ip', rate=get_rate)
def skipif1(request):
# Only rate limit anonymous requests
return HttpResponse()
@ratelimit(key='user_or_ip', rate='10/s')
@ratelimit(key='user_or_ip', rate='100/m')
def burst_limit(request):
# Implement a separate burst limit.
return HttpResponse()
@ratelimit(group='expensive', key='user_or_ip', rate='10/h')
def expensive_view_a(request):
return something_expensive()
@ratelimit(group='expensive', key='user_or_ip', rate='10/h')
def expensive_view_b(request):
# Shares a counter with expensive_view_a
return something_else_expensive()
@ratelimit(key='header:x-cluster-client-ip')
def post(request):
# Uses the X-Cluster-Client-IP header value.
return HttpResponse()
@ratelimit(key=lambda g, r: r.META.get('HTTP_X_CLUSTER_CLIENT_IP',
r.META['REMOTE_ADDR'])
def myview(request):
# Use `X-Cluster-Client-IP` but fall back to REMOTE_ADDR.
return HttpResponse()
Class-Based Views
-----------------
.. versionadded:: 0.5
.. versionchanged:: 3.0
To use the ``@ratelimit`` decorator with class-based views, use the
Django ``@method_decorator``:
.. code-block:: python
from django.utils.decorators import method_decorator
from django.views.generic import View
class MyView(View):
@method_decorator(ratelimit(key='ip', rate='1/m', method='GET'))
def get(self, request):
pass
@method_decorator(ratelimit(key='ip', rate='1/m', method='GET'), name='get')
class MyOtherView(View):
def get(self, request):
pass
It is also possible to wrap a whole view later, e.g.:
.. code-block:: python
from django.urls import path
from myapp.views import MyView
from django_ratelimit.decorators import ratelimit
urlpatterns = [
path('/', ratelimit(key='ip', method='GET', rate='1/m')(MyView.as_view())),
]
.. warning::
Make sure the ``method`` argument matches the method decorated.
.. note::
Unless given an explicit ``group`` argument, different methods of a
class-based view will be limited separately.
.. _usage-helper:
Core Methods
============
.. versionadded:: 3.0
In some cases the decorator is not flexible enough to, e.g.,
conditionally apply rate limits. In these cases, you can access the core
functionality in ``ratelimit.core``. The two major methods are
``get_usage`` and ``is_ratelimited``.
.. code-block:: python
from django_ratelimit.core import get_usage, is_ratelimited
.. py:function:: get_usage(request, group=None, fn=None, key=None, \
rate=None, method=ALL, increment=False)
:arg request:
*None* The HTTPRequest object.
:arg group:
*None* A group of rate limits to count together. Defaults to the
dotted name of the view.
:arg fn:
*None* A view function which can be used to calculate the group
as if it was decorated by :ref:`@ratelimit <usage-decorator>`.
:arg key:
What key to use, see :ref:`Keys <keys-chapter>`.
:arg rate:
*'5/m'* The number of requests per unit time allowed. Valid
units are:
* ``s`` - seconds
* ``m`` - minutes
* ``h`` - hours
* ``d`` - days
Also accepts callables. See :ref:`Rates <rates-chapter>`.
:arg method:
*ALL* Which HTTP method(s) to rate-limit. May be a string, a
list/tuple, or ``None`` for all methods.
:arg increment:
*False* Whether to increment the count or just check.
:returns dict or None:
Either returns None, indicating that ratelimiting was not active
for this request (for some reason) or returns a dict including
the current count, limit, time left in the window, and whether
this request should be limited.
.. py:function:: is_ratelimited(request, group=None, fn=None, \
key=None, rate=None, method=ALL, \
increment=False)
:arg request:
*None* The HTTPRequest object.
:arg group:
*None* A group of rate limits to count together. Defaults to the
dotted name of the view.
:arg fn:
*None* A view function which can be used to calculate the group
as if it was decorated by :ref:`@ratelimit <usage-decorator>`.
:arg key:
What key to use, see :ref:`Keys <keys-chapter>`.
:arg rate:
*'5/m'* The number of requests per unit time allowed. Valid
units are:
* ``s`` - seconds
* ``m`` - minutes
* ``h`` - hours
* ``d`` - days
Also accepts callables. See :ref:`Rates <rates-chapter>`.
:arg method:
*ALL* Which HTTP method(s) to rate-limit. May be a string, a
list/tuple, or ``None`` for all methods.
:arg increment:
*False* Whether to increment the count or just check.
:returns bool:
Whether this request should be limited or not.
``is_ratelimited`` is a thin wrapper around ``get_usage`` that is
maintained for compatibility. It provides strictly less information.
.. warning::
``get_usage`` and ``is_ratelimited`` require either ``group=`` or
``fn=`` to be passed, or they cannot determine the rate limiting
state and will throw.
.. _usage-exception:
Exceptions
==========
.. py:class:: ratelimit.exceptions.Ratelimited
If a request is ratelimited and ``block`` is set to ``True``,
Ratelimit will raise ``ratelimit.exceptions.Ratelimited``.
This is a subclass of Django's ``PermissionDenied`` exception, so
if you don't need any special handling beyond the built-in 403
processing, you don't have to do anything.
If you are setting |handler403|_ in your root URLconf, you can catch this
exception in your custom view to return a different response, for example:
.. code-block:: python
def handler403(request, exception=None):
if isinstance(exception, Ratelimited):
return HttpResponse('Sorry you are blocked', status=429)
return HttpResponseForbidden('Forbidden')
.. |handler403| replace:: ``handler403``
.. _handler403: https://docs.djangoproject.com/en/2.1/topics/http/urls/#error-handling
.. _usage-middleware:
Middleware
==========
There is optional middleware to use a custom view to handle ``Ratelimited``
exceptions.
To use it, add ``django_ratelimit.middleware.RatelimitMiddleware`` to your
``MIDDLEWARE`` (toward the bottom of the list) and set
``RATELIMIT_VIEW`` to the full path of a view you want to use.
The view specified in ``RATELIMIT_VIEW`` will get two arguments, the
``request`` object (after ratelimit processing) and the exception.
|