core.contrib.ratelimit¶
Request-level rate limiter using App Engine Memcache.
Registers as a 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¶
Classes¶
Rate-limit budget for a single time window. |
|
Global HTTP request rate limiter. |
Module Contents¶
- core.contrib.ratelimit.logger¶
- core.contrib.ratelimit._memcache¶
- class core.contrib.ratelimit.TimeWindow¶
Rate-limit budget for a single time window.
- Parameters:
limit – Maximum number of requests allowed within time_window.
time_window – Length of the window in seconds.
- limit: int¶
- time_window: int¶
- class core.contrib.ratelimit.RequestRateLimit(rate_for_guests=TimeWindow(limit=1000, time_window=60), rate_for_users=TimeWindow(limit=2000, time_window=60), namespace='viur_rate_limit')¶
Bases:
viur.core.request.RequestValidatorGlobal 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-Afterheader so clients know when to retry.- Parameters:
rate_for_guests (TimeWindow) – Budget applied to unauthenticated requests.
rate_for_users (TimeWindow) – Budget applied to authenticated requests.
namespace (str) – Memcache namespace used for all rate-limit keys.
- name = 'RequestRateLimit'¶
- rate_for_guests¶
- rate_for_users¶
- namespace = 'viur_rate_limit'¶
- 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)
- Parameters:
request (viur.core.request.Router) – The Request instance to check
- Returns:
None on success, an Error-Tuple otherwise
- Return type:
Optional[tuple[int, str, str]]
- static _get_request_ip()¶
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.
- Return type:
str