Ratelimiter

1.2.0.post0 · maintenance · verified Sun Apr 12

The `ratelimiter` library provides a simple mechanism for rate-limiting operations in Python, both synchronously (using decorators or context managers) and asynchronously (using `async with`). It allows developers to control the frequency of function calls, often useful when interacting with APIs that have usage limits. The current version is 1.2.0.post0, and the project has not seen updates since 2017, suggesting it is no longer actively maintained.

Warnings

Install

Imports

Quickstart

Demonstrates both decorator and context manager usage of `RateLimiter`. It defines a limit of 2 calls per 3-second period and includes a callback to inform when rate-limiting occurs. The `time.sleep` calls simulate work and illustrate how the limiter pauses execution.

import time
from ratelimiter import RateLimiter

def limited_function():
    print(f"Function called at {time.time()}")

def callback_function(until):
    duration = int(round(until - time.time()))
    print(f'Rate limited, sleeping for {duration} seconds')

# Using as a decorator
@RateLimiter(max_calls=2, period=3, callback=callback_function)
def do_something_decorated(item):
    print(f"Processing item {item} (decorated)")

print("--- Decorator Example ---")
for i in range(5):
    do_something_decorated(i)
    time.sleep(0.5) # Simulate some work between calls

# Using as a context manager
rate_limiter_cm = RateLimiter(max_calls=2, period=3, callback=callback_function)

print("\n--- Context Manager Example ---")
for i in range(5):
    with rate_limiter_cm:
        print(f"Processing item {i} (context manager)")
    time.sleep(0.5) # Simulate some work between calls

view raw JSON →