Ratelimit Decorator

2.2.1 · active · verified Thu Apr 09

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.

Warnings

Install

Imports

Quickstart

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`.

import time
from ratelimit import limits, sleep_and_retry, RateLimitException

CALLS = 5
PERIOD = 10 # seconds

@sleep_and_retry
@limits(calls=CALLS, period=PERIOD)
def call_mock_api(url):
    """Simulates an API call that is rate-limited."""
    print(f"Calling API for {url} at {time.strftime('%X')}")
    # Simulate some work or actual API request
    return f"Response from {url}"

if __name__ == "__main__":
    print(f"Limiting to {CALLS} calls per {PERIOD} seconds.\n")
    urls_to_fetch = [f"http://example.com/data/{i}" for i in range(10)]
    
    for url in urls_to_fetch:
        try:
            result = call_mock_api(url)
            # print(result) # Uncomment to see individual results
        except RateLimitException as e:
            print(f"Caught RateLimitException for {url}: {e}")
            # If sleep_and_retry wasn't used, this catch block would be essential.
            # With sleep_and_retry, this block might only be hit if something else fails.
        time.sleep(0.1) # Small delay to make output clearer
    print("\nFinished all simulated API calls.")

view raw JSON →