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, FixedWindow
from upstash_redis import Redis
ratelimit = Ratelimit(
redis=Redis.from_env(),
limiter=FixedWindow(max_requests=10, window=10),
prefix="@upstash/ratelimit",
)
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.dataclass
class 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
"""