core.contrib.ratelimit ====================== .. py:module:: core.contrib.ratelimit .. autoapi-nested-parse:: Request-level rate limiter using App Engine Memcache. Registers as a :class:`~viur.core.request.RequestValidator` and therefore runs *before* any session, routing, or handler logic — making it the earliest possible place to shed excess traffic. Guests are identified by their IP address (IPv6 addresses are bucketed into /64 prefixes so that a single host cannot trivially rotate around the limit). Authenticated users are identified by their Datastore user key. Usage:: from viur.core.request import Router from viur.core.contrib.ratelimit import RequestRateLimit, TimeWindow Router.requestValidators.append( RequestRateLimit( rate_for_guests=TimeWindow(limit=200, time_window=60), rate_for_users=TimeWindow(limit=500, time_window=60), ) ) Attributes ---------- .. autoapisummary:: core.contrib.ratelimit.logger core.contrib.ratelimit._memcache Classes ------- .. autoapisummary:: core.contrib.ratelimit.TimeWindow core.contrib.ratelimit.RequestRateLimit Module Contents --------------- .. py:data:: logger .. py:data:: _memcache .. py:class:: TimeWindow Rate-limit budget for a single time window. :param limit: Maximum number of requests allowed within *time_window*. :param time_window: Length of the window in seconds. .. py:attribute:: limit :type: int .. py:attribute:: time_window :type: int .. py:class:: RequestRateLimit(rate_for_guests = TimeWindow(limit=1000, time_window=60), rate_for_users = TimeWindow(limit=2000, time_window=60), namespace = 'viur_rate_limit') Bases: :py:obj:`viur.core.request.RequestValidator` Global HTTP request rate limiter. Enforces separate budgets for anonymous (guest) and authenticated requests. When the budget is exceeded the validator returns HTTP 429 and sets the ``Retry-After`` header so clients know when to retry. :param rate_for_guests: Budget applied to unauthenticated requests. :param rate_for_users: Budget applied to authenticated requests. :param namespace: Memcache namespace used for all rate-limit keys. .. py:attribute:: name :value: 'RequestRateLimit' .. py:attribute:: rate_for_guests .. py:attribute:: rate_for_users .. py:attribute:: namespace :value: 'viur_rate_limit' .. py:method:: validate(request) The function that checks the current request. If the request is valid, simply return None. If the request should be blocked, it must return a tuple of - The HTTP status code (as int) - The Description of that status code (eg "Forbidden") - The Response Body (can be a simple string or an HTML-Page) :param request: The Request instance to check :return: None on success, an Error-Tuple otherwise .. py:method:: _get_request_ip() :staticmethod: Return a stable client identifier derived from the remote address. IPv4 addresses are returned as-is. For IPv6 the /64 network prefix is returned so that a single host cannot trivially rotate its interface identifier to bypass the limit.