Slowing down. Last release over 3 years ago, little activity since. Fine for existing code; think twice for a new project.
pip install asgi-ratelimitASGI RateLimit
Limit user access frequency. Base on ASGI.
100% coverage. High performance. Support regular matching. Customizable.
Install
# Only install
pip install asgi-ratelimit
# Use redis
pip install asgi-ratelimit[redis]
# Use jwt
pip install asgi-ratelimit[jwt]
# Install all
pip install asgi-ratelimit[full]
Usage
The following example will limit users under the "default" group to access /towns at most once per second and /forests at most once per minute. And the users in the "admin" group have no restrictions.
from typing import Tuple
from ratelimit import RateLimitMiddleware, Rule
# Simple rate-limiter in memory:
from ratelimit.backends.simple import MemoryBackend
rate_limit = RateLimitMiddleware(
ASGI_APP,
AUTH_FUNCTION,
MemoryBackend(),
{
r"^/towns": [Rule(second=1, group="default"), Rule(group="admin")],
r"^/forests": [Rule(minute=1, group="default"), Rule(group="admin")],
},
)
# with Redis:
from redis.asyncio import StrictRedis
from ratelimit.backends.redis import RedisBackend
rate_limit = RateLimitMiddleware(
ASGI_APP,
AUTH_FUNCTION,
RedisBackend(StrictRedis()),
{
r"^/towns": [Rule(second=1, group="default"), Rule(group="admin")],
r"^/forests": [Rule(minute=1, group="default"), Rule(group="admin")],
},
)
:warning: The pattern's order is important, rules are set on the first match: Be careful here !
Next, provide a custom authenticate function, or use one of the existing auth methods.
from ratelimit.auths import EmptyInformation
async def AUTH_FUNCTION(scope: Scope) -> Tuple[str, str]:
"""
Resolve the user's unique identifier and the user's group from ASGI SCOPE.
If there is no user information, it should raise `EmptyInformation`.
If there is no group information, it should return "default".
"""
# FIXME
# You must write the logic of this function yourself,
# or use the function in the following document directly.
return USER_UNIQUE_ID, GROUP_NAME
rate_limit = RateLimitMiddleware(ASGI_APP, AUTH_FUNCTION, ...)
The Rule type takes a time unit (e.g. "second"), a "group", and a "method" as a param. If the "group" param is not specified then the "authenticate" method needs to return the "default group". The "method" param corresponds to the http method, if it is not specified, the rule will be applied to all http requests.