Ratelimit (PY)

Getting Started

Install

pip install upstash-ratelimit

Create database

To be able to use upstash-ratelimit, you need to create a database on Upstash.

Usage

For possible Redis client configurations, have a look at the Redis SDK repository.

This library supports asyncio as well. To use it, import the asyncio-based variant from the upstash_ratelimit.asyncio module.

from upstash_ratelimit import Ratelimit, FixedWindowfrom upstash_redis import Redis# Create a new ratelimiter, that allows 10 requests per 10 secondsratelimit = Ratelimit(    redis=Redis.from_env(),    limiter=FixedWindow(max_requests=10, window=10),    # Optional prefix for the keys used in Redis. This is useful    # if you want to share a Redis instance with other applications    # and want to avoid key collisions. The default prefix is    # "@upstash/ratelimit"    prefix="@upstash/ratelimit",)# Use a constant string to limit all requests with a single ratelimit# Or use a user ID, API key or IP address for individual limits.identifier = "api"response = ratelimit.limit(identifier)if not response.allowed:    print("Unable to process at this time")else:    do_expensive_calculation()    print("Here you go!")

The limit method also returns the following metadata:

@dataclasses.dataclassclass Response:    allowed: bool    """    Whether the request may pass(`True`) or exceeded the limit(`False`)    """    limit: int    """    Maximum number of requests allowed within a window.    """    remaining: int    """    How many requests the user has left within the current window.    """    reset: float    """    Unix timestamp in seconds when the limits are reset    """
Loading search…