Install ratelimit via pip
masterYou can install the ratelimit package directly using pip, or include it in your requirements.txt file for dependency management.
$ pip install ratelimitrepository·master·Indexed 19 days ago
https://github.com/tomasbasham/ratelimitA Python package providing function decorators to prevent functions from being called more frequently than allowed by API providers. It includes the @limits decorator to restrict calls based on a specified number of invocations and time period, and the @sleep_and_retry decorator to pause execution instead of raising a RateLimitException.
You can install the ratelimit package directly using pip, or include it in your requirements.txt file for dependency management.
$ pip install ratelimitTo install the latest version directly from the source code, clone the repository and run the setup script.
$ git clone https://github.com/tomasbasham/ratelimit
$ cd ratelimit
$ python setup.py installWhen using @limits, you can catch the ratelimit.RateLimitException to implement custom retry logic, such as exponential backoff using the backoff library.
from ratelimit import limits, RateLimitException
from backoff import on_exception, expo
import requests
FIFTEEN_MINUTES = 900
@on_exception(expo, RateLimitException, max_tries=8)
@limits(calls=15, period=FIFTEEN_MINUTES)
def call_api(url):
response = requests.get(url)
if response.status_code != 200:
raise Exception('API response: {}'.format(response.status_code))
return responseIf you prefer to halt the current thread until the rate limit period has elapsed rather than handling an exception, use the @sleep_and_retry decorator in conjunction with @limits. This ensures every function invocation eventually succeeds, but it blocks the thread.
from ratelimit import limits, sleep_and_retry
import requests
FIFTEEN_MINUTES = 900
@sleep_and_retry
@limits(calls=15, period=FIFTEEN_MINUTES)
def call_api(url):
response = requests.get(url)
if response.status_code != 200:
raise Exception('API response: {}'.format(response.status_code))
return responseThe @limits decorator prevents a function from being called more often than allowed by an API provider. It accepts two arguments:
calls: The number of allowed invocations.period: The time window in seconds. If not specified, it defaults to 900 seconds (15 minutes).If the limit is exceeded, the decorator raises a ratelimit.RateLimitException.
from ratelimit import limits
import requests
FIFTEEN_MINUTES = 900
@limits(calls=15, period=FIFTEEN_MINUTES)
def call_api(url):
response = requests.get(url)
if response.status_code != 200:
raise Exception('API response: {}'.format(response.status_code))
return response