Skip to main content

No project description provided

Project description

ASGI RateLimit

Limit user access frequency. Base on ASGI.

100% coverage. High performance. 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 /second_limit at most once per second and /minute_limit at most once per minute. And the users in the "admin" group have no restrictions.

from typing import Tuple

from ratelimit import RateLimitMiddleware, Rule
from ratelimit.auths import EmptyInformation
from ratelimit.backends.redis import RedisBackend


async def AUTH_FUNCTION(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".
    """
    return USER_UNIQUE_ID, GROUP_NAME


rate_limit = RateLimitMiddleware(
    ASGI_APP,
    AUTH_FUNCTION,
    RedisBackend(),
    {
        r"^/second_limit": [Rule(second=1), Rule(group="admin")],
        r"^/minute_limit": [Rule(minute=1), Rule(group="admin")],
    },
)

# Or in starlette/fastapi/index.py
app.add_middleware(
    RateLimitMiddleware,
    authenticate=AUTH_FUNCTION,
    backend=RedisBackend(),
    config={
        r"^/second_limit": [Rule(second=1), Rule(group="admin")],
        r"^/minute_limit": [Rule(minute=1), Rule(group="admin")],
    },
)

Built-in auth functions

Client IP

from ratelimit.auths.ip import client_ip

Obtain user IP through scope["client"] or X-Real-IP.

Starlette Session

from ratelimit.auths.session import from_session

Get user and group from scope["session"].

If key group not in session, will return default. If key user not in session, will raise a EmptyInformation.

Json Web Token

from ratelimit.auths.jwt import create_jwt_auth

jwt_auth = create_jwt_auth("KEY", "HS256")

Get user and group from JWT that in Authorization header.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

asgi-ratelimit-0.2.0.tar.gz (10.8 kB view hashes)

Uploaded source

Built Distribution

asgi_ratelimit-0.2.0-py3-none-any.whl (12.6 kB view hashes)

Uploaded py3

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page