from upstash_ratelimit import Ratelimit, FixedWindow
from upstash_redis import Redis
# Create a new ratelimiter, that allows 10 requests per 10 seconds
ratelimit = 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!")