The `ratelimit` library provides a simple, yet powerful, API rate limiting decorator for Python functions. It allows developers to easily control the frequency at which a function can be called, preventing abuse or excessive resource consumption. Currently at version 2.2.1, it follows a stable release cadence, with updates primarily for bug fixes and compatibility.
pip install ratelimitVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to apply a rate limit to a function using the `limits` decorator. The `sleep_and_retry` decorator automatically pauses execution until the rate limit period resets, preventing `RateLimitException` from being raised directly. If `sleep_and_retry` is omitted, you must manually catch `RateLimitException`.
Update decorator usage from `@ratelimit(N, S)` to `@limits(calls=N, period=S)`. Ensure `RateLimitException` is imported directly if catching.
For distributed or multi-process environments, implement a custom storage backend (e.g., using Redis) by subclassing `ratelimit.BaseProxy` and passing an instance to the `limits` decorator's `rate_limiter` argument.
For `async def` functions, wrap the rate-limited synchronous function call in `loop.run_in_executor()` or use an `async` native rate-limiting library. If the actual I/O within your `async` function is blocked by the synchronous decorator, consider refactoring.
Either always use `@sleep_and_retry` for automatic handling or explicitly wrap calls to rate-limited functions in `try...except RateLimitException` blocks to manage the error gracefully.
pip install ratelimit
from ratelimit import ratelimit
@ratelimit(rate=5, per=60) # Allow 5 calls per 60 seconds
def my_function():
return "Hello"from ratelimit import ratelimit
from ratelimit.uses import sleep_and_retry
@sleep_and_retry
@ratelimit(rate=1, per=1) # Allow 1 call per second
def my_function_with_retry():
return "Retrying hello"from ratelimit.exceptions import RateLimitException
try:
# Call your rate-limited function here
result = my_rate_limited_function()
except RateLimitException:
print("Rate limit hit, please wait and retry after some time.")No dependency data recorded yet.