swh.web.api.throttling module#

class swh.web.api.throttling.SwhWebRateThrottle[source]#

Bases: ScopedRateThrottle

Custom DRF request rate limiter for anonymous users

Requests are grouped into scopes. It enables to apply different requests rate limiting based on the scope name but also the input HTTP request types.

To associate a scope to requests, one must add a ‘throttle_scope’ attribute when using a class based view, or call the ‘throttle_scope’ decorator when using a function based view. By default, requests do not have an associated scope and are not rate limited.

Rate limiting can also be configured according to the type of the input HTTP requests for fine grained tuning.

For instance, the following YAML configuration section sets a rate of:
  • 1 per minute for POST requests

  • 60 per minute for other request types

for the ‘swh_api’ scope while exempting those coming from the 127.0.0.0/8 ip network.

throttling:
    scopes:
        swh_api:
            limiter_rate:
                default: 60/m
                POST: 1/m
            exempted_networks:
                - 127.0.0.0/8
scope = None#
get_cache_key(request, view)[source]#

If view.throttle_scope is not set, don’t apply this throttle.

Otherwise generate the unique cache key by concatenating the user id with the .throttle_scope property of the view.

get_exempted_networks(scope_name: str) List[IPv4Network | IPv6Network][source]#
get_scope(view: APIView)[source]#
allow_request(request: Request, view: APIView) bool[source]#

Implement the check to see if the request should be throttled.

On success calls throttle_success. On failure calls throttle_failure.

class swh.web.api.throttling.SwhWebUserRateThrottle[source]#

Bases: SwhWebRateThrottle

Custom DRF request rate limiter for authenticated users

It has the same behavior than swh.web.api.throttling.SwhWebRateThrottle except the number of allowed requests for each throttle scope is increased by a 1Ox factor.

NUM_REQUESTS_FACTOR = 10#
get_cache_key(request, view)[source]#

If view.throttle_scope is not set, don’t apply this throttle.

Otherwise generate the unique cache key by concatenating the user id with the .throttle_scope property of the view.

parse_rate(rate)[source]#

Given the request rate string, return a two tuple of: <allowed number of requests>, <period of time in seconds>

allow_request(request: Request, view: APIView) bool[source]#

Implement the check to see if the request should be throttled.

On success calls throttle_success. On failure calls throttle_failure.

swh.web.api.throttling.throttle_scope(scope: str) Callable[[...], APIView][source]#

Decorator that allows the throttle scope of a DRF function based view to be set:

@api_view(['GET', ])
@throttle_scope('scope')
def view(request):
    ...