Throttling

Provide mixins for throttling/rate limiting in views.

Depends on django-axes.

Todo

Decouple from django-axes - make IP address getter function configurable.

class maykin_common.throttling.IPThrottleMixin

Same behavior as ThrottleMixin except it limits the amount of tries per IP-address a user can access a certain view.

get_throttle_identifier()
class maykin_common.throttling.ThrottleMixin

A very simple throttling implementation with, hopefully, sane defaults.

You can specifiy the amount of visits (throttle_visits) a view can get, for a specific period (in seconds) throttle_period.

check_rate_limit_exceeded() bool

Determine if the rate limit is exceeded or not.

The limit is considered exceeded when:

  • the request matches the conditions to be throttled

  • the amount of visits in the time window exceeds the maximum allowed

dispatch(request, *args, **kwargs)
get_throttle_cache() django.core.cache.backends.base.BaseCache
get_throttle_identifier() str
handle_rate_limit_exceeded() django.http.HttpResponseBase

Return the appropriate response for throttled requests.

Override this to customize behaviour. By default, an HTTP 429 response is returned.

request: django.http.HttpRequest
should_be_throttled() bool

Determine if throttling is enabled for the request.

throttle_403 = False

Marker to opt-in to return 403 responses.

DeprecationWarning - implement ThrottleMixin.handle_rate_limit_exceeded() instead or use the default 429 response.

Changed in version 0.7.0: The default is changed to return 429 instead of 403 and the attribute has been deprecated.

throttle_cache = 'default'

Name of the cache (in settings.CACHES) to use to track visits.

Note

Ensure you use a globally shared cached. Local memory caches are limited to their respective Python process and not aware of other processes/caches.

throttle_methods: Container[str] | Literal['all'] = ('post', 'put', 'patch', 'delete', 'head', 'trace')
throttle_name = 'default'

Identifier for the throttle, used in the cache key.

throttle_period = 3600

Period/time window (in seconds) in which the visits are counted.

Visits older than this window are discarded.

throttle_visits = 100

Number of allowed visits in the specified period.